Refactor Storage Program (#3622)

* Refactor Storage Program

* Replace KeyedAccount trait with StorageAccount struct

* Implement State for Account, not StorageAccount

* Make State trait more generic

* Move validation check into function
This commit is contained in:
Sagar Dhawan
2019-04-04 12:01:09 -07:00
committed by GitHub
parent 1598a02a7a
commit 0b23af324b
5 changed files with 467 additions and 382 deletions

View File

@ -45,6 +45,14 @@ impl Account {
executable: false,
}
}
pub fn deserialize_data<T: serde::de::DeserializeOwned>(&self) -> Result<T, bincode::Error> {
bincode::deserialize(&self.data)
}
pub fn serialize_data<T: serde::Serialize>(&mut self, state: &T) -> Result<(), bincode::Error> {
bincode::serialize_into(&mut self.data[..], state)
}
}
#[repr(C)]

View File

@ -1,6 +1,7 @@
use crate::account::KeyedAccount;
use crate::account::{Account, KeyedAccount};
use crate::instruction::InstructionError;
use crate::pubkey::Pubkey;
use bincode::ErrorKind;
// All native programs export a symbol named process()
pub const ENTRYPOINT: &str = "process";
@ -29,3 +30,37 @@ macro_rules! solana_entrypoint(
}
)
);
/// Conveinence trait to covert bincode errors to instruction errors.
pub trait State<T> {
fn state(&self) -> Result<T, InstructionError>;
fn set_state(&mut self, state: &T) -> Result<(), InstructionError>;
}
impl<T> State<T> for Account
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<'a, T> State<T> for KeyedAccount<'a>
where
T: serde::Serialize + serde::de::DeserializeOwned,
{
fn state(&self) -> Result<T, InstructionError> {
self.account.state()
}
fn set_state(&mut self, state: &T) -> Result<(), InstructionError> {
self.account.set_state(state)
}
}