1 | use crate::parser::errors::ParserError; |
2 | use std::str::FromStr; |
3 | use tinystr::TinyStr4; |
4 | |
5 | #[derive (Debug, PartialEq, Eq, Clone, Hash, PartialOrd, Ord, Copy)] |
6 | pub struct Region(TinyStr4); |
7 | |
8 | impl Region { |
9 | pub fn from_bytes(v: &[u8]) -> Result<Self, ParserError> { |
10 | let slen = v.len(); |
11 | |
12 | match slen { |
13 | 2 => { |
14 | let s = TinyStr4::from_bytes(v).map_err(|_| ParserError::InvalidSubtag)?; |
15 | if !s.is_ascii_alphabetic() { |
16 | return Err(ParserError::InvalidSubtag); |
17 | } |
18 | Ok(Self(s.to_ascii_uppercase())) |
19 | } |
20 | 3 => { |
21 | let s = TinyStr4::from_bytes(v).map_err(|_| ParserError::InvalidSubtag)?; |
22 | if !s.is_ascii_numeric() { |
23 | return Err(ParserError::InvalidSubtag); |
24 | } |
25 | Ok(Self(s)) |
26 | } |
27 | _ => Err(ParserError::InvalidSubtag), |
28 | } |
29 | } |
30 | |
31 | pub fn as_str(&self) -> &str { |
32 | self.0.as_str() |
33 | } |
34 | |
35 | /// # Safety |
36 | /// |
37 | /// This function accepts any u64 that is exected to be a valid |
38 | /// `TinyStr4` and a valid `Region` subtag. |
39 | pub const unsafe fn from_raw_unchecked(v: u32) -> Self { |
40 | Self(TinyStr4::from_bytes_unchecked(v.to_le_bytes())) |
41 | } |
42 | } |
43 | |
44 | impl From<Region> for u32 { |
45 | fn from(input: Region) -> Self { |
46 | u32::from_le_bytes(*input.0.all_bytes()) |
47 | } |
48 | } |
49 | |
50 | impl<'l> From<&'l Region> for &'l str { |
51 | fn from(input: &'l Region) -> Self { |
52 | input.0.as_str() |
53 | } |
54 | } |
55 | |
56 | impl FromStr for Region { |
57 | type Err = ParserError; |
58 | |
59 | fn from_str(source: &str) -> Result<Self, Self::Err> { |
60 | Self::from_bytes(source.as_bytes()) |
61 | } |
62 | } |
63 | |
64 | impl std::fmt::Display for Region { |
65 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { |
66 | f.write_str(&self.0) |
67 | } |
68 | } |
69 | |
70 | impl PartialEq<&str> for Region { |
71 | fn eq(&self, other: &&str) -> bool { |
72 | self.as_str() == *other |
73 | } |
74 | } |
75 | |