Implement `FromStr` for Network constant

This commit is contained in:
Aleksei Sidorov 2018-05-16 12:22:07 +03:00
parent 6f3c7e19dd
commit 3224cf2b18
2 changed files with 21 additions and 0 deletions

View File

@ -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<Self, Self::Err> {
match s {
$($txt => Ok($name::$elem)),*,
_ => Err(::serde::de::Error::syntax(stringify!(s)))
}
}
}
impl ::serde::Deserialize for $name { impl ::serde::Deserialize for $name {
#[inline] #[inline]
fn deserialize<D>(d: &mut D) -> Result<$name, D::Error> fn deserialize<D>(d: &mut D) -> Result<$name, D::Error>

View File

@ -84,5 +84,15 @@ mod tests {
let bad: Result<Network, _> = deserialize("fakenet".as_bytes()); let bad: Result<Network, _> = deserialize("fakenet".as_bytes());
assert!(bad.is_err()); 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::<Network>().is_err());
}
} }