use std::borrow::Cow;
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Locale {
tag: Cow<'static, str>,
}
impl Locale {
pub const EN_US: Locale = Locale::from_static("en-US");
pub const DE_DE: Locale = Locale::from_static("de-DE");
pub const FR_FR: Locale = Locale::from_static("fr-FR");
pub const fn from_static(tag: &'static str) -> Self {
Self {
tag: Cow::Borrowed(tag),
}
}
pub fn tag(&self) -> &str {
&self.tag
}
}
impl Default for Locale {
fn default() -> Self {
Self::EN_US
}
}
impl From<String> for Locale {
fn from(tag: String) -> Self {
Self {
tag: Cow::Owned(tag),
}
}
}
impl From<&str> for Locale {
fn from(tag: &str) -> Self {
Self {
tag: Cow::Owned(tag.to_string()),
}
}
}
impl std::fmt::Display for Locale {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.tag)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_locale_is_us_english() {
assert_eq!(Locale::default(), Locale::EN_US);
assert_eq!(Locale::EN_US.tag(), "en-US");
}
#[test]
fn a_built_in_tag_borrows() {
assert!(matches!(Locale::DE_DE.tag, Cow::Borrowed(_)));
}
#[test]
fn a_tag_obtained_at_runtime_owns_itself() {
let from_data = format!("{}-{}", "ar", "EG");
let loc = Locale::from(from_data);
assert_eq!(loc.tag(), "ar-EG");
assert!(matches!(loc.tag, Cow::Owned(_)));
}
#[test]
fn a_tag_is_carried_verbatim() {
assert_ne!(Locale::from("ar_EG"), Locale::from("ar-EG"));
assert_eq!(Locale::from("ar_EG").tag(), "ar_EG");
}
#[test]
fn display_is_the_tag() {
assert_eq!(Locale::FR_FR.to_string(), "fr-FR");
}
}