Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 22 additions & 6 deletions instructions-sysvar/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,9 +161,13 @@ pub fn load_current_index_checked(
}

/// Store the current `Instruction`'s index in the instructions sysvar data.
pub fn store_current_index(data: &mut [u8], instruction_index: u16) {
pub fn store_current_index(data: &mut [u8], instruction_index: u16) -> Result<(), ProgramError> {
if data.len() < 2 {
return Err(ProgramError::AccountDataTooSmall);
}
let last_index = data.len() - 2;
data[last_index..last_index + 2].copy_from_slice(&instruction_index.to_le_bytes());
Ok(())
}

#[cfg_attr(feature = "dev-context-only-utils", qualifiers(pub))]
Expand Down Expand Up @@ -289,13 +293,21 @@ mod tests {
#[test]
fn test_load_store_instruction() {
let mut data = [4u8; 10];
store_current_index(&mut data, 3);
let res = store_current_index(&mut data, 3);
assert!(res.is_ok());
#[allow(deprecated)]
let index = load_current_index(&data);
assert_eq!(index, 3);
assert_eq!([4u8; 8], data[0..8]);
}

#[test]
fn test_store_instruction_too_small_data() {
let mut data = [4u8; 1];
let res = store_current_index(&mut data, 3);
assert!(res.is_err());
}

#[derive(Copy, Clone)]
struct MakeInstructionParams {
program_id: Pubkey,
Expand Down Expand Up @@ -422,7 +434,8 @@ mod tests {
let key = id();
let mut lamports = 0;
let mut data = construct_instructions_data(&[borrowed_instruction0, borrowed_instruction1]);
store_current_index(&mut data, 1);
let res = store_current_index(&mut data, 1);
assert!(res.is_ok());
let owner = solana_sdk_ids::sysvar::id();
let mut account_info = AccountInfo::new(
&key,
Expand All @@ -438,7 +451,8 @@ mod tests {
assert_eq!(1, load_current_index_checked(&account_info).unwrap());
{
let mut data = account_info.try_borrow_mut_data().unwrap();
store_current_index(&mut data, 0);
let res = store_current_index(&mut data, 0);
assert!(res.is_ok());
}
assert_eq!(0, load_current_index_checked(&account_info).unwrap());

Expand Down Expand Up @@ -490,7 +504,8 @@ mod tests {
borrowed_instruction1,
borrowed_instruction2,
]);
store_current_index(&mut data, 1);
let res = store_current_index(&mut data, 1);
assert!(res.is_ok());
let owner = solana_sdk_ids::sysvar::id();
let mut account_info = AccountInfo::new(
&key,
Expand Down Expand Up @@ -525,7 +540,8 @@ mod tests {
);
{
let mut data = account_info.try_borrow_mut_data().unwrap();
store_current_index(&mut data, 0);
let res = store_current_index(&mut data, 0);
assert!(res.is_ok());
}
assert_eq!(
Err(ProgramError::InvalidArgument),
Expand Down