use different ser/de for Script in case of non human readable format

This commit is contained in:
Riccardo Casatta 2021-04-26 11:52:19 +02:00
parent b0ae2a6842
commit fadd368911
No known key found for this signature in database
GPG Key ID: FD986A969E450397
1 changed files with 48 additions and 29 deletions

View File

@ -819,44 +819,59 @@ impl_index_newtype!(Builder, u8);
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Script { impl<'de> serde::Deserialize<'de> for Script {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where where D: serde::Deserializer<'de>,
D: serde::Deserializer<'de>,
{ {
use core::fmt::Formatter; use core::fmt::Formatter;
use hashes::hex::FromHex; use hashes::hex::FromHex;
if deserializer.is_human_readable() {
struct Visitor; struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor { impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = Script; type Value = Script;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result { fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("a script") formatter.write_str("a script hex")
} }
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where where E: serde::de::Error,
E: serde::de::Error,
{ {
let v = Vec::from_hex(v).map_err(E::custom)?; let v = Vec::from_hex(v).map_err(E::custom)?;
Ok(Script::from(v)) Ok(Script::from(v))
} }
fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E> fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
where where E: serde::de::Error,
E: serde::de::Error,
{ {
self.visit_str(v) self.visit_str(v)
} }
fn visit_string<E>(self, v: String) -> Result<Self::Value, E> fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where where E: serde::de::Error,
E: serde::de::Error,
{ {
self.visit_str(&v) self.visit_str(&v)
} }
} }
deserializer.deserialize_str(Visitor) deserializer.deserialize_str(Visitor)
} else {
struct BytesVisitor;
impl<'de> serde::de::Visitor<'de> for BytesVisitor {
type Value = Script;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("a script Vec<u8>")
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where E: serde::de::Error,
{
Ok(Script::from(v.to_vec()))
}
}
deserializer.deserialize_bytes(BytesVisitor)
}
} }
} }
@ -867,7 +882,11 @@ impl serde::Serialize for Script {
where where
S: serde::Serializer, S: serde::Serializer,
{ {
if serializer.is_human_readable() {
serializer.serialize_str(&format!("{:x}", self)) serializer.serialize_str(&format!("{:x}", self))
} else {
serializer.serialize_bytes(&self.as_bytes())
}
} }
} }