1use crate::parser::errors::ParserError;
2use std::borrow::Borrow;
3use std::convert::TryFrom;
4use std::str::FromStr;
5use tinystr::TinyStr8;
6
7#[derive(Default, Debug, PartialEq, Eq, Clone, Hash, PartialOrd, Ord, Copy)]
8pub struct Language(Option<TinyStr8>);
9
10impl Language {
11 pub fn from_bytes(v: &[u8]) -> Result<Self, ParserError> {
12 let slen = v.len();
13
14 let s = TinyStr8::from_bytes(v).map_err(|_| ParserError::InvalidLanguage)?;
15 if !(2..=8).contains(&slen) || slen == 4 || !s.is_ascii_alphabetic() {
16 return Err(ParserError::InvalidLanguage);
17 }
18
19 let value = s.to_ascii_lowercase();
20
21 if value == "und" {
22 Ok(Self(None))
23 } else {
24 Ok(Self(Some(value)))
25 }
26 }
27
28 pub fn as_str(&self) -> &str {
29 self.0.as_deref().unwrap_or("und")
30 }
31
32 /// # Safety
33 ///
34 /// This function accepts any u64 that is exected to be a valid
35 /// `TinyStr8` and a valid `Language` subtag.
36 pub const unsafe fn from_raw_unchecked(v: u64) -> Self {
37 Self(Some(TinyStr8::from_bytes_unchecked(v.to_le_bytes())))
38 }
39
40 pub fn matches<O: Borrow<Self>>(
41 self,
42 other: O,
43 self_as_range: bool,
44 other_as_range: bool,
45 ) -> bool {
46 (self_as_range && self.0.is_none())
47 || (other_as_range && other.borrow().0.is_none())
48 || self == *other.borrow()
49 }
50
51 pub fn clear(&mut self) {
52 self.0 = None;
53 }
54
55 pub fn is_empty(self) -> bool {
56 self.0.is_none()
57 }
58}
59
60impl From<Language> for Option<u64> {
61 fn from(input: Language) -> Self {
62 input.0.map(|i: TinyAsciiStr<8>| u64::from_le_bytes(*i.all_bytes()))
63 }
64}
65
66impl From<&Language> for Option<u64> {
67 fn from(input: &Language) -> Self {
68 input.0.map(|i: TinyAsciiStr<8>| u64::from_le_bytes(*i.all_bytes()))
69 }
70}
71
72impl<T> TryFrom<Option<T>> for Language
73where
74 T: AsRef<[u8]>,
75{
76 type Error = ParserError;
77
78 fn try_from(v: Option<T>) -> Result<Self, Self::Error> {
79 match v {
80 Some(l: T) => Ok(Self::from_bytes(l.as_ref())?),
81 None => Ok(Self(None)),
82 }
83 }
84}
85
86impl FromStr for Language {
87 type Err = ParserError;
88
89 fn from_str(source: &str) -> Result<Self, Self::Err> {
90 Self::from_bytes(source.as_bytes())
91 }
92}
93
94impl std::fmt::Display for Language {
95 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
96 if let Some(ref lang: &TinyAsciiStr<8>) = self.0 {
97 f.write_str(data:lang)
98 } else {
99 f.write_str(data:"und")
100 }
101 }
102}
103
104impl PartialEq<&str> for Language {
105 fn eq(&self, other: &&str) -> bool {
106 self.as_str() == *other
107 }
108}
109