Add Rust BPF RefCell borrow helpers (#8047)
This commit is contained in:
@ -1,5 +1,9 @@
|
||||
use crate::{account::Account, pubkey::Pubkey};
|
||||
use std::{cell::RefCell, cmp, fmt, rc::Rc};
|
||||
use crate::{account::Account, program_error::ProgramError, pubkey::Pubkey};
|
||||
use std::{
|
||||
cell::{Ref, RefCell, RefMut},
|
||||
cmp, fmt,
|
||||
rc::Rc,
|
||||
};
|
||||
|
||||
/// Account information
|
||||
#[derive(Clone)]
|
||||
@ -55,14 +59,50 @@ impl<'a> AccountInfo<'a> {
|
||||
**self.lamports.borrow()
|
||||
}
|
||||
|
||||
pub fn try_lamports(&self) -> Result<u64, ProgramError> {
|
||||
Ok(**self.try_borrow_lamports()?)
|
||||
}
|
||||
|
||||
pub fn data_len(&self) -> usize {
|
||||
self.data.borrow().len()
|
||||
}
|
||||
|
||||
pub fn try_data_len(&self) -> Result<usize, ProgramError> {
|
||||
Ok(self.try_borrow_data()?.len())
|
||||
}
|
||||
|
||||
pub fn data_is_empty(&self) -> bool {
|
||||
self.data.borrow().is_empty()
|
||||
}
|
||||
|
||||
pub fn try_data_is_empty(&self) -> Result<bool, ProgramError> {
|
||||
Ok(self.try_borrow_data()?.is_empty())
|
||||
}
|
||||
|
||||
pub fn try_borrow_lamports(&self) -> Result<Ref<&mut u64>, ProgramError> {
|
||||
self.lamports
|
||||
.try_borrow()
|
||||
.map_err(|_| ProgramError::AccountBorrowFailed)
|
||||
}
|
||||
|
||||
pub fn try_borrow_mut_lamports(&self) -> Result<RefMut<&'a mut u64>, ProgramError> {
|
||||
self.lamports
|
||||
.try_borrow_mut()
|
||||
.map_err(|_| ProgramError::AccountBorrowFailed)
|
||||
}
|
||||
|
||||
pub fn try_borrow_data(&self) -> Result<Ref<&mut [u8]>, ProgramError> {
|
||||
self.data
|
||||
.try_borrow()
|
||||
.map_err(|_| ProgramError::AccountBorrowFailed)
|
||||
}
|
||||
|
||||
pub fn try_borrow_mut_data(&self) -> Result<RefMut<&'a mut [u8]>, ProgramError> {
|
||||
self.data
|
||||
.try_borrow_mut()
|
||||
.map_err(|_| ProgramError::AccountBorrowFailed)
|
||||
}
|
||||
|
||||
pub fn new(
|
||||
key: &'a Pubkey,
|
||||
is_signer: bool,
|
||||
|
@ -75,10 +75,10 @@ pub enum InstructionError {
|
||||
/// The instruction expected an executable account
|
||||
AccountNotExecutable,
|
||||
|
||||
/// Failed to borrow a reference to an account, already borrowed
|
||||
/// Failed to borrow a reference to account data, already borrowed
|
||||
AccountBorrowFailed,
|
||||
|
||||
/// Account has an outstanding reference after a program's execution
|
||||
/// Account data has an outstanding reference after a program's execution
|
||||
AccountBorrowOutstanding,
|
||||
|
||||
/// The same account was multiply passed to an on-chain program's entrypoint, but the program
|
||||
|
@ -30,7 +30,7 @@ pub enum ProgramError {
|
||||
UninitializedAccount,
|
||||
/// The instruction expected additional account keys
|
||||
NotEnoughAccountKeys,
|
||||
/// Failed to borrow a reference to an account, already borrowed
|
||||
/// Failed to borrow a reference to account data, already borrowed
|
||||
AccountBorrowFailed,
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user