Merge rust-bitcoin/rust-bitcoin#2846: generate Network <-> Magic From and TryFrom with a macro

76826313a1 generate Network <-> Magic From and TryFrom with a macro (Antoni Spaanderman)

Pull request description:

  Removes possible errors when a network is added to the enum (expressed with the comment `// Note: new network entries must explicitly be matched in 'try_from' below.`)

ACKs for top commit:
  Kixunil:
    ACK 76826313a1
  apoelstra:
    ACK 76826313a1

Tree-SHA512: 37aaf4b9021204c24e3dc405e666f3dea8c4f8e478b26892dd962a49c988904ba02c3dee7cec1ad78d4e4bb9ba9565ec4574d0e169dd215d26b010f1c4dd3d0b
This commit is contained in:
Andrew Poelstra 2024-06-10 13:24:56 +00:00
commit f934132b3b
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
1 changed files with 29 additions and 22 deletions

View File

@ -243,14 +243,14 @@ impl FromStr for Magic {
} }
} }
macro_rules! generate_network_magic_conversion {
($(Network::$network:ident => Magic::$magic:ident,)*) => {
impl From<Network> for Magic { impl From<Network> for Magic {
fn from(network: Network) -> Magic { fn from(network: Network) -> Magic {
match network { match network {
// Note: new network entries must explicitly be matched in `try_from` below. $(
Network::Bitcoin => Magic::BITCOIN, Network::$network => Magic::$magic,
Network::Testnet => Magic::TESTNET, )*
Network::Signet => Magic::SIGNET,
Network::Regtest => Magic::REGTEST,
} }
} }
} }
@ -260,15 +260,22 @@ impl TryFrom<Magic> for Network {
fn try_from(magic: Magic) -> Result<Self, Self::Error> { fn try_from(magic: Magic) -> Result<Self, Self::Error> {
match magic { match magic {
// Note: any new network entries must be matched against here. $(
Magic::BITCOIN => Ok(Network::Bitcoin), Magic::$magic => Ok(Network::$network),
Magic::TESTNET => Ok(Network::Testnet), )*
Magic::SIGNET => Ok(Network::Signet),
Magic::REGTEST => Ok(Network::Regtest),
_ => Err(UnknownMagicError(magic)), _ => Err(UnknownMagicError(magic)),
} }
} }
} }
};
}
generate_network_magic_conversion! {
Network::Bitcoin => Magic::BITCOIN,
Network::Testnet => Magic::TESTNET,
Network::Signet => Magic::SIGNET,
Network::Regtest => Magic::REGTEST,
}
impl fmt::Display for Magic { impl fmt::Display for Magic {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {