Skip to content

Instantly share code, notes, and snippets.

@JayKickliter
Last active April 14, 2020 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JayKickliter/52ae527946b9b10ebb6870accd8b4b45 to your computer and use it in GitHub Desktop.
Save JayKickliter/52ae527946b9b10ebb6870accd8b4b45 to your computer and use it in GitHub Desktop.
Parse from hex, decimal, or binary
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