Skip to content

Commit

Permalink
Add additional utils (#9)
Browse files Browse the repository at this point in the history
* add bytes_20_hex

* add bytes_20_hex

* add bytes_20_hex

* add address utils

* add address utils

* add b256 utils

* remove ssz feature flag
  • Loading branch information
eserilev authored Aug 15, 2024
1 parent a706030 commit c4667a0
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ categories = ["cryptography::cryptocurrencies"]
name = "serde_utils"

[dependencies]
alloy-primitives = { version = "0.7.0", features = ["ssz", "serde"] }
alloy-primitives = { version = "0.7.7", features = ["serde"] }
serde = { version = "1.0.0", features = ["derive"] }
serde_derive = "1.0.0"
serde_json = "1.0.0"
Expand Down
34 changes: 34 additions & 0 deletions src/address_hex.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use alloy_primitives::Address;
use serde::de::Error;
use serde::{Deserializer, Serializer};

use crate::hex::PrefixedHexVisitor;

pub fn serialize<S>(address: &Address, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut hex_string: String = "0x".to_string();
hex_string.push_str(&hex::encode(&address));

serializer.serialize_str(&hex_string)
}

pub fn deserialize<'de, D>(deserializer: D) -> Result<Address, D::Error>
where
D: Deserializer<'de>,
{
let decoded = deserializer.deserialize_str(PrefixedHexVisitor)?;

if decoded.len() != 20 {
return Err(D::Error::custom(format!(
"expected {} bytes for array, got {}",
20,
decoded.len()
)));
}

let mut array = [0; 20];
array.copy_from_slice(&decoded);
Ok(array.into())
}
34 changes: 34 additions & 0 deletions src/b256_hex.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use alloy_primitives::B256;
use serde::de::Error;
use serde::{Deserializer, Serializer};

use crate::hex::PrefixedHexVisitor;

pub fn serialize<S>(hash: &B256, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut hex_string: String = "0x".to_string();
hex_string.push_str(&hex::encode(&hash));

serializer.serialize_str(&hex_string)
}

pub fn deserialize<'de, D>(deserializer: D) -> Result<B256, D::Error>
where
D: Deserializer<'de>,
{
let decoded = deserializer.deserialize_str(PrefixedHexVisitor)?;

if decoded.len() != 32 {
return Err(D::Error::custom(format!(
"expected {} bytes for array, got {}",
32,
decoded.len()
)));
}

let mut array = [0; 32];
array.copy_from_slice(&decoded);
Ok(array.into())
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
mod quoted_int;

pub mod address_hex;
pub mod b256_hex;
pub mod fixed_bytes_hex;
pub mod hex;
pub mod hex_vec;
Expand Down

0 comments on commit c4667a0

Please sign in to comment.