feat(codec): add hex encode and decode functions (#1059)

This commit is contained in:
Matthias Seitz 2022-03-18 06:08:50 +01:00 committed by GitHub
parent c9ef5769e2
commit dd4893a752
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 21 additions and 1 deletions

View File

@ -9,12 +9,28 @@ use crate::{
pub trait AbiEncode { pub trait AbiEncode {
/// ABI encode the type /// ABI encode the type
fn encode(self) -> Vec<u8>; fn encode(self) -> Vec<u8>;
/// Returns the encoded value as hex string, _with_ a `0x` prefix
fn encode_hex(self) -> String
where
Self: Sized,
{
format!("0x{}", hex::encode(self.encode()))
}
} }
/// Trait for ABI decoding /// Trait for ABI decoding
pub trait AbiDecode: Sized { pub trait AbiDecode: Sized {
/// Decodes the ABI encoded data /// Decodes the ABI encoded data
fn decode(bytes: impl AsRef<[u8]>) -> Result<Self, AbiError>; fn decode(bytes: impl AsRef<[u8]>) -> Result<Self, AbiError>;
/// Decode hex encoded ABI encoded data
///
/// Expects a hex encoded string, with optional `0x` prefix
fn decode_hex(data: impl AsRef<str>) -> Result<Self, AbiError> {
let bytes: Bytes = data.as_ref().parse()?;
Self::decode(bytes)
}
} }
macro_rules! impl_abi_codec { macro_rules! impl_abi_codec {

View File

@ -24,6 +24,7 @@ pub(crate) use _format_err as format_err;
macro_rules! _bail { macro_rules! _bail {
($($tt:tt)*) => { return Err($crate::abi::error::format_err!($($tt)*)) }; ($($tt:tt)*) => { return Err($crate::abi::error::format_err!($($tt)*)) };
} }
use crate::types::ParseBytesError;
pub(crate) use _bail as bail; pub(crate) use _bail as bail;
/// ABI codec related errors /// ABI codec related errors
@ -39,4 +40,7 @@ pub enum AbiError {
#[error("missing or wrong function selector")] #[error("missing or wrong function selector")]
WrongSelector, WrongSelector,
#[error(transparent)]
ParseBytesError(#[from] ParseBytesError),
} }

View File

@ -25,7 +25,7 @@ mod i256;
pub use i256::{Sign, I256}; pub use i256::{Sign, I256};
mod bytes; mod bytes;
pub use self::bytes::Bytes; pub use self::bytes::{Bytes, ParseBytesError};
mod block; mod block;
pub use block::{Block, BlockId, BlockNumber}; pub use block::{Block, BlockId, BlockNumber};