From 3224cf2b18399847ed8b6ac22ce2aee5ecd870f8 Mon Sep 17 00:00:00 2001 From: Aleksei Sidorov Date: Wed, 16 May 2018 12:22:07 +0300 Subject: [PATCH] Implement `FromStr` for Network constant --- src/macros.rs | 11 +++++++++++ src/network/constants.rs | 10 ++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/macros.rs b/src/macros.rs index 24eedb5d..f937b5e2 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -105,6 +105,17 @@ macro_rules! user_enum { } } + impl ::std::str::FromStr for $name { + type Err = ::serde::de::value::Error; + #[inline] + fn from_str(s: &str) -> Result { + match s { + $($txt => Ok($name::$elem)),*, + _ => Err(::serde::de::Error::syntax(stringify!(s))) + } + } + } + impl ::serde::Deserialize for $name { #[inline] fn deserialize(d: &mut D) -> Result<$name, D::Error> diff --git a/src/network/constants.rs b/src/network/constants.rs index 5cff16e5..228f78c4 100644 --- a/src/network/constants.rs +++ b/src/network/constants.rs @@ -84,5 +84,15 @@ mod tests { let bad: Result = deserialize("fakenet".as_bytes()); assert!(bad.is_err()); } + + #[test] + fn string_test() { + assert_eq!(Network::Bitcoin.to_string(), "bitcoin"); + assert_eq!(Network::Testnet.to_string(), "testnet"); + + assert_eq!("bitcoin".parse(), Ok(Network::Bitcoin)); + assert_eq!("testnet".parse(), Ok(Network::Testnet)); + assert!("fakenet".parse::().is_err()); + } }