Merge rust-bitcoin/rust-bitcoin#1801: Adds as_core_arg serde module to network

aa6a3530a6 Adds as_core_arg serde module to network (Sergi Delgado Segura)

Pull request description:

  The new module provides serde functions to convert from/to Bitcoin Core network variants.

  Fixes #1799

ACKs for top commit:
  Kixunil:
    ACK aa6a3530a6
  tcharding:
    ACK aa6a3530a6
  sanket1729:
    ACK aa6a3530a6

Tree-SHA512: f536d0e41144928b71dc9b58735d4e0b883ee84a7a84e868f1d74b284c2e2be746ddcb30028dd099515bc933e7efa2cf26717f506edde84c40c3f523a5a8ed27
This commit is contained in:
Andrew Poelstra 2023-05-01 23:44:26 +00:00
commit 67ff453a3a
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
1 changed files with 67 additions and 0 deletions

View File

@ -172,6 +172,52 @@ impl Network {
} }
} }
#[cfg(feature = "serde")]
pub mod as_core_arg {
//! Module for serialization/deserialization of network variants into/from Bitcoin Core values
#![allow(missing_docs)]
use serde;
use crate::Network;
pub fn serialize<S>(network: &Network, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(network.to_core_arg())
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Network, D::Error>
where
D: serde::Deserializer<'de>,
{
struct NetworkVisitor;
impl<'de> serde::de::Visitor<'de> for NetworkVisitor {
type Value = Network;
fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<Self::Value, E> {
Network::from_core_arg(s).map_err(|_| {
E::invalid_value(
serde::de::Unexpected::Str(s),
&"bitcoin network encoded as a string (either main, test, signet or regtest)",
)
})
}
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(
formatter,
"bitcoin network encoded as a string (either main, test, signet or regtest)"
)
}
}
deserializer.deserialize_str(NetworkVisitor)
}
}
/// An error in parsing network string. /// An error in parsing network string.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseNetworkError(String); pub struct ParseNetworkError(String);
@ -670,4 +716,25 @@ mod tests {
assert_eq!(net.to_core_arg(), *core_arg); assert_eq!(net.to_core_arg(), *core_arg);
} }
} }
#[cfg(feature = "serde")]
#[test]
fn serde_as_core_arg() {
#[derive(Serialize, Deserialize, PartialEq, Debug)]
#[serde(crate = "actual_serde")]
struct T {
#[serde(with = "crate::network::constants::as_core_arg")]
pub network: Network,
}
serde_test::assert_tokens(
&T { network: Network::Bitcoin },
&[
serde_test::Token::Struct { name: "T", len: 1 },
serde_test::Token::Str("network"),
serde_test::Token::Str("main"),
serde_test::Token::StructEnd,
],
);
}
} }