solana/sdk/src/account_utils.rs

89 lines
2.6 KiB
Rust
Raw Normal View History

//! Useful extras for `Account` state.
use {
crate::{
account::{Account, AccountSharedData},
instruction::InstructionError,
},
bincode::ErrorKind,
std::cell::Ref,
};
2019-05-21 15:19:41 -07:00
2019-05-21 17:13:21 -07:00
/// Convenience trait to covert bincode errors to instruction errors.
2020-01-22 17:54:06 -08:00
pub trait StateMut<T> {
2019-05-21 15:19:41 -07:00
fn state(&self) -> Result<T, InstructionError>;
fn set_state(&mut self, state: &T) -> Result<(), InstructionError>;
}
2020-01-22 17:54:06 -08:00
pub trait State<T> {
fn state(&self) -> Result<T, InstructionError>;
fn set_state(&self, state: &T) -> Result<(), InstructionError>;
}
2019-05-21 15:19:41 -07:00
2020-01-22 17:54:06 -08:00
impl<T> StateMut<T> for Account
2019-05-21 15:19:41 -07:00
where
T: serde::Serialize + serde::de::DeserializeOwned,
{
fn state(&self) -> Result<T, InstructionError> {
self.deserialize_data()
.map_err(|_| InstructionError::InvalidAccountData)
}
fn set_state(&mut self, state: &T) -> Result<(), InstructionError> {
self.serialize_data(state).map_err(|err| match *err {
ErrorKind::SizeLimit => InstructionError::AccountDataTooSmall,
_ => InstructionError::GenericError,
})
}
}
2021-03-09 13:06:07 -08:00
impl<T> StateMut<T> for AccountSharedData
where
T: serde::Serialize + serde::de::DeserializeOwned,
{
fn state(&self) -> Result<T, InstructionError> {
self.deserialize_data()
.map_err(|_| InstructionError::InvalidAccountData)
}
fn set_state(&mut self, state: &T) -> Result<(), InstructionError> {
self.serialize_data(state).map_err(|err| match *err {
ErrorKind::SizeLimit => InstructionError::AccountDataTooSmall,
_ => InstructionError::GenericError,
})
}
}
impl<T> StateMut<T> for Ref<'_, AccountSharedData>
where
T: serde::Serialize + serde::de::DeserializeOwned,
{
fn state(&self) -> Result<T, InstructionError> {
self.deserialize_data()
.map_err(|_| InstructionError::InvalidAccountData)
}
fn set_state(&mut self, _state: &T) -> Result<(), InstructionError> {
panic!("illegal");
}
}
2019-05-21 15:19:41 -07:00
#[cfg(test)]
mod tests {
use {
super::*,
crate::{account::AccountSharedData, pubkey::Pubkey},
};
2019-05-21 15:19:41 -07:00
#[test]
fn test_account_state() {
let state = 42u64;
2021-03-09 13:06:07 -08:00
assert!(AccountSharedData::default().set_state(&state).is_err());
let res = AccountSharedData::default().state() as Result<u64, InstructionError>;
2019-05-21 15:19:41 -07:00
assert!(res.is_err());
2021-03-09 13:06:07 -08:00
let mut account = AccountSharedData::new(0, std::mem::size_of::<u64>(), &Pubkey::default());
2019-05-21 15:19:41 -07:00
assert!(account.set_state(&state).is_ok());
let stored_state: u64 = account.state().unwrap();
assert_eq!(stored_state, state);
}
}