Skip to content

Commit

Permalink
Merge pull request #115 from ralexstokes/hex-serde
Browse files Browse the repository at this point in the history
allow optional `0x` prefix on hex {en,de}coding
  • Loading branch information
ralexstokes authored Nov 3, 2023
2 parents 9687857 + c0a21cb commit 7e6986d
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 30 deletions.
4 changes: 2 additions & 2 deletions ssz-rs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,10 @@ mod lib {
array::TryFromSliceError,
fmt::{Debug, Display, Formatter},
ops::{Deref, DerefMut, Index, IndexMut},
slice::{IterMut, SliceIndex},
slice::SliceIndex,
str::FromStr,
},
iter::{Enumerate, ExactSizeIterator},
iter::ExactSizeIterator,
};

#[cfg(not(feature = "std"))]
Expand Down
30 changes: 2 additions & 28 deletions ssz-rs/src/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,8 @@ use hex::FromHexError;

const HEX_ENCODING_PREFIX: &str = "0x";

#[derive(Debug)]
pub enum HexError {
Hex(FromHexError),
MissingPrefix,
}

impl fmt::Display for HexError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Hex(e) => write!(f, "{e}"),
Self::MissingPrefix => {
write!(f, "missing prefix `{HEX_ENCODING_PREFIX}` when deserializing hex data")
}
}
}
}

impl From<FromHexError> for HexError {
fn from(e: FromHexError) -> Self {
Self::Hex(e)
}
}

#[cfg(feature = "std")]
impl std::error::Error for HexError {}

pub fn try_bytes_from_hex_str(s: &str) -> Result<Vec<u8>, HexError> {
let target = s.strip_prefix(HEX_ENCODING_PREFIX).ok_or(HexError::MissingPrefix)?;
pub fn try_bytes_from_hex_str(s: &str) -> Result<Vec<u8>, FromHexError> {
let target = s.strip_prefix(HEX_ENCODING_PREFIX).unwrap_or(s);
let data = hex::decode(target)?;
Ok(data)
}
Expand Down

0 comments on commit 7e6986d

Please sign in to comment.