Last active
April 14, 2020 20:24
-
-
Save JayKickliter/52ae527946b9b10ebb6870accd8b4b45 to your computer and use it in GitHub Desktop.
Parse from hex, decimal, or binary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait FromHexDecBin: Sized { | |
type Error; | |
fn from_hex_dec_bin(s: &str) -> Result<Self, Self::Error>; | |
} | |
macro_rules! impl_from_hex_dec_bin { | |
($T:tt, $E:ty) => { | |
impl FromHexDecBin for $T { | |
type Error = $E; | |
fn from_hex_dec_bin(s: &str) -> Result<$T, Self::Error> { | |
if s.len() > 2 { | |
match s.split_at(2) { | |
("0x", rest) => $T::from_str_radix(rest, 16), | |
("0b", rest) => $T::from_str_radix(rest, 2), | |
_ => $T::from_str_radix(s, 10), | |
} | |
} else { | |
$T::from_str_radix(s, 10) | |
} | |
} | |
} | |
}; | |
} | |
impl_from_hex_dec_bin!(u16, ::std::num::ParseIntError); | |
/// Usage in structopt: | |
/// | |
///``` | |
/// #[structopt(name = "ADDR", default_value = "0x42", parse(try_from_str = u16::from_hex_dec_bin))] | |
/// addr: u16, | |
/// ``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment