Lenient bytes deserialization (#2340)

* Lenient bytes deserialization

* Error when deserializing invalid hex

* Error when deserializing invalid hex

Conflicts:
	rpc/src/v1/types/bytes.rs
This commit is contained in:
Tomasz Drwięga 2016-09-27 11:24:27 +02:00 committed by Gav Wood
parent c3741640f7
commit 16f3119547

View File

@ -70,10 +70,12 @@ impl Visitor for BytesVisitor {
type Value = Bytes; type Value = Bytes;
fn visit_str<E>(&mut self, value: &str) -> Result<Self::Value, E> where E: Error { fn visit_str<E>(&mut self, value: &str) -> Result<Self::Value, E> where E: Error {
if value.len() >= 2 && &value[0..2] == "0x" { if value.is_empty() {
Ok(Bytes::new(FromHex::from_hex(&value[2..]).unwrap_or_else(|_| vec![]))) Ok(Bytes::new(Vec::new()))
} else if value.len() >= 2 && &value[0..2] == "0x" && value.len() & 1 == 0 {
Ok(Bytes::new(try!(FromHex::from_hex(&value[2..]).map_err(|_| Error::custom("invalid hex")))))
} else { } else {
Err(Error::custom("invalid hex")) Err(Error::custom("invalid format"))
} }
} }
@ -95,5 +97,32 @@ mod tests {
let serialized = serde_json::to_string(&bytes).unwrap(); let serialized = serde_json::to_string(&bytes).unwrap();
assert_eq!(serialized, r#""0x0123456789abcdef""#); assert_eq!(serialized, r#""0x0123456789abcdef""#);
} }
#[test]
fn test_bytes_deserialize() {
// TODO [ToDr] Uncomment when Mist starts sending correct data
// let bytes1: Result<Bytes, serde_json::Error> = serde_json::from_str(r#""""#);
let bytes2: Result<Bytes, serde_json::Error> = serde_json::from_str(r#""0x123""#);
let bytes3: Result<Bytes, serde_json::Error> = serde_json::from_str(r#""0xgg""#);
let bytes4: Bytes = serde_json::from_str(r#""0x""#).unwrap();
let bytes5: Bytes = serde_json::from_str(r#""0x12""#).unwrap();
let bytes6: Bytes = serde_json::from_str(r#""0x0123""#).unwrap();
let bytes7: Bytes = serde_json::from_str(r#""0x0123456789abcdef""#).unwrap();
// assert!(bytes1.is_err());
assert!(bytes2.is_err());
assert!(bytes3.is_err());
assert_eq!(bytes4, Bytes(vec![]));
assert_eq!(bytes5, Bytes(vec![0x12]));
assert_eq!(bytes6, Bytes(vec![0x1, 0x23]));
assert_eq!(bytes7, Bytes(vec![0x1, 0x23, 0x45,0x67,0x89, 0xab, 0xcd, 0xef]));
}
#[test]
fn test_bytes_lenient_against_the_spec_deserialize_for_empty_string_for_geth_compatibility() {
let deserialized: Bytes = serde_json::from_str(r#""""#).unwrap();
assert_eq!(deserialized, Bytes(Vec::new()));
}
} }