Skip to content

Commit 8095df2

Browse files
committed
feat(silentpayments): implement serde::{Serialize,Deserialize} for Label
1 parent 327f998 commit 8095df2

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

src/silentpayments/recipient.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,39 @@ impl core::str::FromStr for Label {
110110
}
111111
}
112112
}
113+
114+
#[cfg(feature = "serde")]
115+
impl serde::Serialize for Label {
116+
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
117+
if s.is_human_readable() {
118+
s.collect_str(self)
119+
} else {
120+
s.serialize_bytes(&self.serialize()[..])
121+
}
122+
}
123+
}
124+
125+
#[cfg(feature = "serde")]
126+
impl<'de> serde::Deserialize<'de> for Label {
127+
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
128+
if d.is_human_readable() {
129+
use crate::serde_util::FromStrVisitor;
130+
131+
d.deserialize_str(FromStrVisitor::new(
132+
"a hex string representing a Silent Payment Label",
133+
))
134+
} else {
135+
use crate::serde_util::BytesVisitor;
136+
137+
d.deserialize_bytes(BytesVisitor::new("a raw Silent Payment Label", |slice| {
138+
let bytes: &[u8; 33] = slice.try_into().map_err(|_| LabelError::ParseFailure)?;
139+
140+
Self::parse(bytes)
141+
}))
142+
}
143+
}
144+
}
145+
113146
/// Label errors.
114147
#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash)]
115148
pub enum LabelError {

0 commit comments

Comments
 (0)