Skip to content

Instantly share code, notes, and snippets.

@killercup
Created June 4, 2017 21:44
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 killercup/02ff6d695cde7de8cc7dd52a98f95218 to your computer and use it in GitHub Desktop.
Save killercup/02ff6d695cde7de8cc7dd52a98f95218 to your computer and use it in GitHub Desktop.
macro_rules! enum_with_str_repr {
($enum_name:ident { $($variant:ident => $str:expr),* }) => {
#[derive(PartialEq, PartialOrd, Copy, Clone, Eq, Ord, Hash, Debug)]
pub enum $enum_name {
$(
#[doc=$str]
$variant,
)*
}
impl ::std::fmt::Display for $enum_name {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
fmt.write_str(self.as_ref())
}
}
impl AsRef<str> for $enum_name {
fn as_ref(&self) -> &str {
use $enum_name::*;
match *self {
$(
$variant => $str,
)*
}
}
}
impl ::std::str::FromStr for $enum_name {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
use $enum_name::*;
match s {
$(
$str => Ok($variant),
)*
_ => Err("oh noes".into()),
}
}
}
}
}
enum_with_str_repr!{
HttpVersion {
Http09 => "HTTP/0.9",
Http10 => "HTTP/1.0",
Http11 => "HTTP/1.1",
Http20 => "HTTP/2.0"
}
}
fn main() {
let version: HttpVersion = "HTTP/0.9".parse().unwrap();
println!("version {}", version);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment