From 88cd693ca0402f52067a3b1641f8350c07dfffb7 Mon Sep 17 00:00:00 2001 From: Dr Maxim Orlovsky Date: Thu, 7 Mar 2024 22:02:06 +0100 Subject: [PATCH 1/2] data: support human-readable serde serialization for ByteStr --- src/data/byte_str.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/data/byte_str.rs b/src/data/byte_str.rs index f8d3972..911e565 100644 --- a/src/data/byte_str.rs +++ b/src/data/byte_str.rs @@ -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}; @@ -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) + } } } @@ -301,7 +306,12 @@ mod _serde { where D: Deserializer<'de>, { - let vec = Vec::::deserialize(deserializer)?; + let vec = if deserializer.is_human_readable() { + let hex = String::deserialize(deserializer)?; + Vec::::from_hex(&hex).map_err(D::Error::custom)? + } else { + Vec::::deserialize(deserializer)? + }; ByteStr::try_from(vec.deref()) .map_err(|_| D::Error::invalid_length(vec.len(), &"max u16::MAX bytes")) } From 2ce3f88f6e1cc3220e94714e4ec86641a4bab854 Mon Sep 17 00:00:00 2001 From: Dr Maxim Orlovsky Date: Thu, 7 Mar 2024 22:11:38 +0100 Subject: [PATCH 2/2] chore: fix clippy lint --- src/data/byte_str.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/data/byte_str.rs b/src/data/byte_str.rs index 911e565..2435e81 100644 --- a/src/data/byte_str.rs +++ b/src/data/byte_str.rs @@ -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; }