Skip to content

Commit

Permalink
data: support human-readable serde serialization for ByteStr
Browse files Browse the repository at this point in the history
  • Loading branch information
dr-orlovsky committed Mar 7, 2024
1 parent 0cf6df4 commit 88cd693
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/data/byte_str.rs
Original file line number Diff line number Diff line change
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)

Check warning on line 297 in src/data/byte_str.rs

View check run for this annotation

Codecov / codecov/patch

src/data/byte_str.rs#L296-L297

Added lines #L296 - L297 were not covered by tests
} else {
self.as_ref().serialize(serializer)

Check warning on line 299 in src/data/byte_str.rs

View check run for this annotation

Codecov / codecov/patch

src/data/byte_str.rs#L299

Added line #L299 was not covered by tests
}
}
}

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)?

Check warning on line 311 in src/data/byte_str.rs

View check run for this annotation

Codecov / codecov/patch

src/data/byte_str.rs#L309-L311

Added lines #L309 - L311 were not covered by tests
} else {
Vec::<u8>::deserialize(deserializer)?

Check warning on line 313 in src/data/byte_str.rs

View check run for this annotation

Codecov / codecov/patch

src/data/byte_str.rs#L313

Added line #L313 was not covered by tests
};
ByteStr::try_from(vec.deref())
.map_err(|_| D::Error::invalid_length(vec.len(), &"max u16::MAX bytes"))
}
Expand Down

0 comments on commit 88cd693

Please sign in to comment.