Skip to content

Commit

Permalink
Merge pull request #110 from AluVM/serde_bytestr
Browse files Browse the repository at this point in the history
Support human-readable serde serialization for ByteStr
  • Loading branch information
dr-orlovsky authored Mar 7, 2024
2 parents 0cf6df4 + 2ce3f88 commit 48e2f6b
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/data/byte_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ impl Display for ByteStr {
let mut ctl = false;
for c in s.chars() {
let v = c as u32;
if (c.is_control() && v != 0x20) || v < 0x20 || v >= 0x7F {
if (c.is_control() && v != 0x20) || !(0x20..0x7F).contains(&v) {
if !ctl {
ctl = true;
}
Expand Down Expand Up @@ -282,6 +282,7 @@ mod _serde {
use std::convert::TryFrom;
use std::ops::Deref;

use amplify::hex::{FromHex, ToHex};
use serde_crate::de::Error;
use serde_crate::{Deserialize, Deserializer, Serialize, Serializer};

Expand All @@ -292,7 +293,11 @@ mod _serde {
where
S: Serializer,
{
self.as_ref().serialize(serializer)
if serializer.is_human_readable() {
self.as_ref().to_hex().serialize(serializer)
} else {
self.as_ref().serialize(serializer)
}
}
}

Expand All @@ -301,7 +306,12 @@ mod _serde {
where
D: Deserializer<'de>,
{
let vec = Vec::<u8>::deserialize(deserializer)?;
let vec = if deserializer.is_human_readable() {
let hex = String::deserialize(deserializer)?;
Vec::<u8>::from_hex(&hex).map_err(D::Error::custom)?
} else {
Vec::<u8>::deserialize(deserializer)?
};
ByteStr::try_from(vec.deref())
.map_err(|_| D::Error::invalid_length(vec.len(), &"max u16::MAX bytes"))
}
Expand Down

0 comments on commit 48e2f6b

Please sign in to comment.