Skip to content

Commit

Permalink
fix(utils): bincode ser-/deserialization for BytesToHexSerde (#1947)
Browse files Browse the repository at this point in the history
## What ❔

Only do a hex string conversion if serializer/deserializer
`.is_human_readable()`.

## Why ❔

bincode does not need a hex string presentation.

## Checklist

<!-- Check your PR fulfills the following items. -->
<!-- For draft PRs check the boxes as you complete them. -->

- [x] PR title corresponds to the body of PR (we generate changelog
entries from PRs).
- [x] Tests for the changes have been added / updated.
- [ ] Documentation comments have been added / updated.
- [x] Code has been formatted via `zk fmt` and `zk lint`.
- [ ] Spellcheck has been run via `zk spellcheck`.

Signed-off-by: Harald Hoyer <harald@matterlabs.dev>
  • Loading branch information
haraldh authored May 16, 2024
1 parent e10bbdd commit a75b917
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 11 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions core/lib/utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ itertools.workspace = true
serde_json.workspace = true
rand.workspace = true
tokio = { workspace = true, features = ["macros", "rt"] }
bincode.workspace = true
64 changes: 53 additions & 11 deletions core/lib/utils/src/serde_wrappers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,28 +25,70 @@ impl<P: Prefix> BytesToHexSerde<P> {
where
S: Serializer,
{
// First, serialize to hexadecimal string.
let hex_value = format!("{}{}", P::prefix(), hex::encode(value));
if serializer.is_human_readable() {
// First, serialize to hexadecimal string.
let hex_value = format!("{}{}", P::prefix(), hex::encode(value));

// Then, serialize it using `Serialize` trait implementation for `String`.
String::serialize(&hex_value, serializer)
// Then, serialize it using `Serialize` trait implementation for `String`.
String::serialize(&hex_value, serializer)
} else {
<[u8]>::serialize(value, serializer)
}
}

pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where
D: Deserializer<'de>,
{
let deserialized_string = String::deserialize(deserializer)?;
if deserializer.is_human_readable() {
let deserialized_string = String::deserialize(deserializer)?;

if let Some(deserialized_string) = deserialized_string.strip_prefix(P::prefix()) {
hex::decode(deserialized_string).map_err(de::Error::custom)
if let Some(deserialized_string) = deserialized_string.strip_prefix(P::prefix()) {
hex::decode(deserialized_string).map_err(de::Error::custom)
} else {
Err(de::Error::custom(format!(
"string value missing prefix: {:?}",
P::prefix()
)))
}
} else {
Err(de::Error::custom(format!(
"string value missing prefix: {:?}",
P::prefix()
)))
<Vec<u8>>::deserialize(deserializer)
}
}
}

pub type ZeroPrefixHexSerde = BytesToHexSerde<ZeroxPrefix>;

#[cfg(test)]
mod tests {
use serde::{Deserialize, Serialize};

use crate::ZeroPrefixHexSerde;

#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Execute {
#[serde(with = "ZeroPrefixHexSerde")]
pub calldata: Vec<u8>,
}

#[test]
fn test_hex_serde_bincode() {
let original = Execute {
calldata: vec![0, 1, 2, 3, 4],
};
let encoded: Vec<u8> = vec![5, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4];
let decoded: Execute = bincode::deserialize(&encoded).unwrap();
assert_eq!(original, decoded);
}

#[test]
fn test_hex_serde_json() {
let original = Execute {
calldata: vec![0, 1, 2, 3, 4],
};
let encoded = serde_json::to_string(&original).unwrap();
assert_eq!(r#"{"calldata":"0x0001020304"}"#, encoded);
let decoded: Execute = serde_json::from_str(&encoded).unwrap();
assert_eq!(original, decoded);
}
}

0 comments on commit a75b917

Please sign in to comment.