use core::fmt;
use smol_bytes::Utf8Bytes;
use super::{registry, subtag};
#[cfg(test)]
mod tests;
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Region(Utf8Bytes);
impl Region {
pub fn new(text: &str) -> Result<Self, ParseRegionError> {
if text.is_empty() {
return Err(ParseRegionError::Empty);
}
let letters = text
.chars()
.all(|character| character.is_ascii_alphabetic());
let digits = text.chars().all(|character| character.is_ascii_digit());
let canonical = match (letters, digits) {
(true, _) if text.len() == COUNTRY => subtag::Cased::upper(text).as_str().into(),
(true, _) => return Err(ParseRegionError::WrongLetterWidth),
(_, true) if text.len() == AREA => Utf8Bytes::from(text),
(_, true) => return Err(ParseRegionError::WrongDigitWidth),
_ => match subtag::non_alphanumeric(text) {
Some(outside) => return Err(ParseRegionError::NotAlphanumeric(outside)),
None => return Err(ParseRegionError::Mixed),
},
};
match registry::region_preferred(canonical.as_str()) {
Some(preferred) => Ok(Self(Utf8Bytes::from(preferred))),
None => Ok(Self(canonical)),
}
}
pub const ZZ: Self = Self(Utf8Bytes::from_static("ZZ"));
#[must_use]
pub fn is_zz(&self) -> bool {
*self == Self::ZZ
}
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
self.0.as_str()
}
#[inline]
#[must_use]
pub fn into_inner(self) -> Utf8Bytes {
self.0
}
#[must_use]
pub fn is_area(&self) -> bool {
self.as_str().len() == AREA
}
#[inline]
#[must_use]
pub fn name(&self) -> Option<&'static str> {
registry::region_name(self.as_str())
}
#[inline]
#[must_use]
pub fn is_registered(&self) -> bool {
self.name().is_some()
}
#[inline]
#[must_use]
pub fn is_deprecated(&self) -> bool {
registry::region_is_deprecated(self.as_str())
}
#[inline]
#[must_use]
pub fn is_private_use(&self) -> bool {
registry::region_is_private_use(self.as_str())
}
}
const COUNTRY: usize = 2;
const AREA: usize = 3;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ParseRegionError {
Empty,
WrongLetterWidth,
WrongDigitWidth,
NotAlphanumeric(char),
Mixed,
}
impl fmt::Display for ParseRegionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Empty => {
f.write_str("a region subtag is two letters or three digits, and nothing was sent")
}
Self::WrongLetterWidth => f.write_str("a region subtag written in letters is exactly two"),
Self::WrongDigitWidth => f.write_str("a region subtag written in digits is exactly three"),
Self::NotAlphanumeric(outside) => write!(
f,
"a region subtag is letters or digits, so `{outside}` is not one of its characters"
),
Self::Mixed => {
f.write_str("a region subtag is two letters or three digits, and never a mixture")
}
}
}
}
impl core::error::Error for ParseRegionError {}
super::subtag_citizen!(Region, RegionWire, ParseRegionError, "RegionFilter");