Skip to content

Commit

Permalink
Fix Bytes deserialization for unicode values (#695)
Browse files Browse the repository at this point in the history
  • Loading branch information
popzxc authored Jun 14, 2023
1 parent 10542d7 commit d49ad4f
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions src/types/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ impl<'a> Visitor<'a> for BytesVisitor {
where
E: Error,
{
if value.len() >= 2 && &value[0..2] == "0x" {
let bytes = hex::decode(&value[2..]).map_err(|e| Error::custom(format!("Invalid hex: {}", e)))?;
if let Some(value) = value.strip_prefix("0x") {
let bytes = hex::decode(value).map_err(|e| Error::custom(format!("Invalid hex: {}", e)))?;
Ok(Bytes(bytes))
} else {
Err(Error::invalid_value(Unexpected::Str(value), &"0x prefix"))
Expand All @@ -69,3 +69,28 @@ impl<'a> Visitor<'a> for BytesVisitor {
self.visit_str(value.as_ref())
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn deserialize() {
assert_eq!(serde_json::from_str::<Bytes>(r#""0x00""#).unwrap(), Bytes(vec![0x00]));
assert_eq!(
serde_json::from_str::<Bytes>(r#""0x0123456789AaBbCcDdEeFf""#).unwrap(),
Bytes(vec![0x01, 0x23, 0x45, 0x67, 0x89, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF])
);
assert_eq!(serde_json::from_str::<Bytes>(r#""0x""#).unwrap(), Bytes(vec![]));

assert!(serde_json::from_str::<Bytes>("0").is_err(), "Not a string");
assert!(serde_json::from_str::<Bytes>(r#""""#).is_err(), "Empty string");
assert!(serde_json::from_str::<Bytes>(r#""0xZZ""#).is_err(), "Invalid hex");
assert!(
serde_json::from_str::<Bytes>(r#""deadbeef""#).is_err(),
"Missing 0x prefix"
);
assert!(serde_json::from_str::<Bytes>(r#""数字""#).is_err(), "Non-ASCII");
assert!(serde_json::from_str::<Bytes>(r#""0x数字""#).is_err(), "Non-ASCII");
}
}

0 comments on commit d49ad4f

Please sign in to comment.