Skip to content

Commit

Permalink
[core] Update to use TryFrom
Browse files Browse the repository at this point in the history
  • Loading branch information
shawntabrizi committed Apr 16, 2019
1 parent 4e7baf9 commit 27635f8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 16 deletions.
29 changes: 15 additions & 14 deletions core/src/env/srml/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
// You should have received a copy of the GNU General Public License
// along with pDSL. If not, see <http://www.gnu.org/licenses/>.

use core::convert::TryFrom;
use core::array::TryFromSliceError;

use crate::env::EnvTypes;
use parity_codec::{
Decode,
Expand All @@ -33,13 +36,12 @@ impl EnvTypes for DefaultSrmlTypes {
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encode, Decode)]
pub struct Address(pub [u8; 32]);

impl<'a> From<&'a [u8]> for Address {
fn from(bytes: &'a [u8]) -> Self {
assert_eq!(bytes.len(), 32);
let mut array = [0; 32];
let bytes = &bytes[..array.len()]; // panics if not enough data
array.copy_from_slice(bytes);
Address(array)
impl<'a> TryFrom<&'a [u8]> for Address {
type Error = TryFromSliceError;

fn try_from(bytes: &'a [u8]) -> Result<Address, TryFromSliceError> {
let address = <[u8; 32]>::try_from(bytes)?;
Ok(Address(address))
}
}

Expand All @@ -50,12 +52,11 @@ pub type Balance = u64;
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encode, Decode)]
pub struct Hash(pub [u8; 32]);

impl<'a> From<&'a [u8]> for Hash {
fn from(bytes: &'a [u8]) -> Self {
assert_eq!(bytes.len(), 32);
let mut array = [0; 32];
let bytes = &bytes[..array.len()]; // panics if not enough data
array.copy_from_slice(bytes);
Hash(array)
impl<'a> TryFrom<&'a [u8]> for Hash {
type Error = TryFromSliceError;

fn try_from(bytes: &'a [u8]) -> Result<Hash, TryFromSliceError> {
let hash = <[u8; 32]>::try_from(bytes)?;
Ok(Hash(hash))
}
}
5 changes: 3 additions & 2 deletions core/src/env/test_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with pDSL. If not, see <http://www.gnu.org/licenses/>.

use std::convert::TryFrom;
use super::*;
use crate::{
env::srml,
Expand Down Expand Up @@ -385,8 +386,8 @@ impl EnvStorage for TestEnv {

impl Env for TestEnv
where
<Self as EnvTypes>::Address: for<'a> From<&'a [u8]>,
<Self as EnvTypes>::Hash: for<'a> From<&'a [u8]>,
<Self as EnvTypes>::Address: for<'a> TryFrom<&'a [u8]>,
<Self as EnvTypes>::Hash: for<'a> TryFrom<&'a [u8]>,

{
fn caller() -> <Self as EnvTypes>::Address {
Expand Down

0 comments on commit 27635f8

Please sign in to comment.