Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support human-readable serde serialization for ByteStr #110

Merged
merged 2 commits into from
Mar 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading