solana/sdk/src/account_utils.rs

51 lines
1.6 KiB
Rust
Raw Normal View History

2019-05-21 15:19:41 -07:00
//! useful extras for Account state
use crate::{account::Account, instruction::InstructionError};
2019-05-21 15:19:41 -07:00
use bincode::ErrorKind;
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,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
2020-01-28 16:11:22 -08:00
use crate::{account::Account, pubkey::Pubkey};
2019-05-21 15:19:41 -07:00
#[test]
fn test_account_state() {
let state = 42u64;
assert!(Account::default().set_state(&state).is_err());
let res = Account::default().state() as Result<u64, InstructionError>;
assert!(res.is_err());
let mut account = Account::new(0, std::mem::size_of::<u64>(), &Pubkey::default());
assert!(account.set_state(&state).is_ok());
let stored_state: u64 = account.state().unwrap();
assert_eq!(stored_state, state);
}
}