Skip to content

Commit d49ad4f

Browse files
authored
Fix Bytes deserialization for unicode values (#695)
1 parent 10542d7 commit d49ad4f

1 file changed

Lines changed: 27 additions & 2 deletions

File tree

src/types/bytes.rs

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,8 @@ impl<'a> Visitor<'a> for BytesVisitor {
5454
where
5555
E: Error,
5656
{
57-
if value.len() >= 2 && &value[0..2] == "0x" {
58-
let bytes = hex::decode(&value[2..]).map_err(|e| Error::custom(format!("Invalid hex: {}", e)))?;
57+
if let Some(value) = value.strip_prefix("0x") {
58+
let bytes = hex::decode(value).map_err(|e| Error::custom(format!("Invalid hex: {}", e)))?;
5959
Ok(Bytes(bytes))
6060
} else {
6161
Err(Error::invalid_value(Unexpected::Str(value), &"0x prefix"))
@@ -69,3 +69,28 @@ impl<'a> Visitor<'a> for BytesVisitor {
6969
self.visit_str(value.as_ref())
7070
}
7171
}
72+
73+
#[cfg(test)]
74+
mod tests {
75+
use super::*;
76+
77+
#[test]
78+
fn deserialize() {
79+
assert_eq!(serde_json::from_str::<Bytes>(r#""0x00""#).unwrap(), Bytes(vec![0x00]));
80+
assert_eq!(
81+
serde_json::from_str::<Bytes>(r#""0x0123456789AaBbCcDdEeFf""#).unwrap(),
82+
Bytes(vec![0x01, 0x23, 0x45, 0x67, 0x89, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF])
83+
);
84+
assert_eq!(serde_json::from_str::<Bytes>(r#""0x""#).unwrap(), Bytes(vec![]));
85+
86+
assert!(serde_json::from_str::<Bytes>("0").is_err(), "Not a string");
87+
assert!(serde_json::from_str::<Bytes>(r#""""#).is_err(), "Empty string");
88+
assert!(serde_json::from_str::<Bytes>(r#""0xZZ""#).is_err(), "Invalid hex");
89+
assert!(
90+
serde_json::from_str::<Bytes>(r#""deadbeef""#).is_err(),
91+
"Missing 0x prefix"
92+
);
93+
assert!(serde_json::from_str::<Bytes>(r#""数字""#).is_err(), "Non-ASCII");
94+
assert!(serde_json::from_str::<Bytes>(r#""0x数字""#).is_err(), "Non-ASCII");
95+
}
96+
}

0 commit comments

Comments
 (0)