Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix deserializing owned hex string #35

Merged
merged 1 commit into from
Sep 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading