Account->AccountSharedData (#15691)
This commit is contained in:
committed by
GitHub
parent
61c7ce857e
commit
8a3135d17b
@@ -1,6 +1,7 @@
|
||||
//! useful extras for Account state
|
||||
use crate::{account::Account, instruction::InstructionError};
|
||||
use crate::{account::Account, account::AccountSharedData, instruction::InstructionError};
|
||||
use bincode::ErrorKind;
|
||||
use std::cell::Ref;
|
||||
|
||||
/// Convenience trait to covert bincode errors to instruction errors.
|
||||
pub trait StateMut<T> {
|
||||
@@ -28,20 +29,49 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{account::Account, pubkey::Pubkey};
|
||||
use crate::{account::AccountSharedData, pubkey::Pubkey};
|
||||
|
||||
#[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!(AccountSharedData::default().set_state(&state).is_err());
|
||||
let res = AccountSharedData::default().state() as Result<u64, InstructionError>;
|
||||
assert!(res.is_err());
|
||||
|
||||
let mut account = Account::new(0, std::mem::size_of::<u64>(), &Pubkey::default());
|
||||
let mut account = AccountSharedData::new(0, std::mem::size_of::<u64>(), &Pubkey::default());
|
||||
|
||||
assert!(account.set_state(&state).is_ok());
|
||||
let stored_state: u64 = account.state().unwrap();
|
||||
|
||||
Reference in New Issue
Block a user