Skip to content

Commit

Permalink
remove "0x" on deserialization (#781)
Browse files Browse the repository at this point in the history
  • Loading branch information
benr-ml committed May 8, 2024
1 parent 8f65dad commit 4988a47
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
11 changes: 9 additions & 2 deletions fastcrypto/src/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,18 @@ impl Base64 {
}

/// Hex string encoding.
#[derive(Deserialize, Debug, JsonSchema, Clone)]
#[derive(Deserialize, Debug, JsonSchema, Clone, PartialEq)]
#[serde(try_from = "String")]
pub struct Hex(String);

impl TryFrom<String> for Hex {
type Error = FastCryptoError;
fn try_from(value: String) -> Result<Self, Self::Error> {
let s = value.strip_prefix("0x").unwrap_or(&value);
Ok(Self(s.to_string()))
}
}

impl Serialize for Hex {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand All @@ -130,7 +138,6 @@ impl Serialize for Hex {
}

impl_serde_as_for_encoding!(Hex);
impl_try_from_string!(Hex);

impl Hex {
/// Create a hex encoding from a string.
Expand Down
3 changes: 3 additions & 0 deletions fastcrypto/src/tests/encoding_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,10 @@ fn test_serde() {

let encoded_str = serde_json::to_string(&encoded).unwrap();
let decoded: Hex = serde_json::from_str(&encoded_str).unwrap();
let encoded_str2 = serde_json::to_string(&decoded).unwrap();
assert_eq!("\"0x01\"", encoded_str);
assert_eq!(encoded, decoded);
assert_eq!(encoded_str, encoded_str2);
assert_eq!(
decoded.to_vec().as_ref().unwrap(),
encoded.to_vec().as_ref().unwrap()
Expand Down

0 comments on commit 4988a47

Please sign in to comment.