Skip to content

Instantly share code, notes, and snippets.

@pyfisch
Last active August 29, 2015 14:14
Show Gist options
  • Save pyfisch/91196db6df376c9638a7 to your computer and use it in GitHub Desktop.
Save pyfisch/91196db6df376c9638a7 to your computer and use it in GitHub Desktop.
language.rs
#[plugin] #[no_link]
extern crate phf_macros;
extern crate phf;
use std::fmt;
use std::str::FromStr;
use std::ascii::AsciiExt;
#[derive(Clone, Debug, PartialOrd, PartialEq)]
pub enum Language {
Ar,
De,
En,
Fr,
Sl,
Extension(String),
}
static LANGUAGE_FROM_STR: phf::Map<&'static str, Language> = phf_map! {
"ar" => Language::Ar,
"de" => Language::De,
"en" => Language::En,
"fr" => Language::Fr,
"sl" => Language::Sl,
};
/*static STR_FROM_LANGUAGE: phf::Map<Language, &'static str> = phf_map! {
Language::Ar => "ar",
Language::De => "de",
Language::En => "en",
Language::Fr => "fr",
Language::Sl => "sl",
};*/
pub fn parse_language(key: &str) -> Option<Language> {
LANGUAGE_FROM_STR.get(key).map(|t| t.clone())
}
pub fn fmt_language(key: &Language) -> Option<&str> {
Some("foobar")//STR_FROM_LANGUAGE.get(key).map(|t| t.clone())
}
impl FromStr for Language {
fn from_str(mut s: &str) -> Option<Language> {
let slice = &s.to_ascii_lowercase()[];
Some(match parse_language(slice) {
Some(lang) => lang,
None => Language::Extension(slice.to_string()),
})
}
}
impl fmt::Display for Language {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match fmt_language(self) {
Some(ref string) => string.as_slice(),
None => match *self {
Language::Extension(ref string) => &**string,
_ => panic!("WTF"),
},
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment