Skip to content

Commit

Permalink
Merge pull request #35 from blckngm/fix-serde
Browse files Browse the repository at this point in the history
fix: fix deserializing owned hex string
  • Loading branch information
zhangsoledad authored Sep 6, 2023
2 parents 635076e + 9e971ae commit ba216aa
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ exclude = [
]

[dependencies]
serde = { version = "1.0", optional = true, features = ["derive"]}
serde = { version = "1.0", optional = true }

[features]
default = ["std", "serde"]
Expand Down
22 changes: 17 additions & 5 deletions src/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ mod internal {
decode::{hex_decode_with_case, CheckCase},
encode::hex_encode_custom,
};
use alloc::borrow::Cow;
use serde::{de::Error, Deserializer, Serializer};
use std::iter::FromIterator;

Expand Down Expand Up @@ -50,16 +51,16 @@ mod internal {
D: Deserializer<'de>,
T: FromIterator<u8>,
{
let raw_src: &[u8] = serde::Deserialize::deserialize(deserializer)?;
if with_prefix && (raw_src.len() < 2 || raw_src[0] != b'0' || raw_src[1] != b'x') {
let raw_src: Cow<str> = serde::Deserialize::deserialize(deserializer)?;
if with_prefix && !raw_src.starts_with("0x") {
return Err(D::Error::custom("invalid prefix".to_string()));
}

let src: &[u8] = {
if with_prefix {
&raw_src[2..]
raw_src[2..].as_bytes()
} else {
raw_src
raw_src.as_bytes()
}
};

Expand Down Expand Up @@ -94,7 +95,6 @@ where
}

/// Generate module with serde methods
#[macro_export]
macro_rules! faster_hex_serde_macros {
($mod_name:ident, $with_pfx:expr, $check_case:expr) => {
/// Serialize and deserialize with or without 0x-prefix,
Expand Down Expand Up @@ -162,6 +162,18 @@ mod tests {
bar: Vec<u8>,
}

#[test]
fn test_deserialize_escaped() {
// 0x03 but escaped.
let x: Simple = serde_json::from_str(
r#"{
"bar": "\u0030x\u00303"
}"#,
)
.unwrap();
assert_eq!(x.bar, b"\x03");
}

fn _test_simple(src: &str) {
let simple = Simple { bar: src.into() };
let result = serde_json::to_string(&simple);
Expand Down

0 comments on commit ba216aa

Please sign in to comment.