1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use serde::{de, Deserialize, Deserializer, Serialize};
use std::fmt;
#[derive(Debug, Clone, Serialize, Hash, Eq, PartialEq)]
pub struct CountryTag(String);
impl CountryTag {
pub fn new(x: String) -> Self {
debug_assert!(
x.len() == 3,
"expected country tag {} to be 3 characters",
x
);
CountryTag(x)
}
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
impl<'a> From<&'a str> for CountryTag {
fn from(x: &'a str) -> Self {
CountryTag::from(String::from(x))
}
}
impl From<String> for CountryTag {
fn from(x: String) -> Self {
CountryTag::new(x)
}
}
impl Into<String> for CountryTag {
fn into(self) -> String {
self.0
}
}
impl fmt::Display for CountryTag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl<'de> Deserialize<'de> for CountryTag {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct CountryTagVisitor;
impl<'de> de::Visitor<'de> for CountryTagVisitor {
type Value = CountryTag;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("struct CountryTag")
}
fn visit_str<A>(self, v: &str) -> Result<Self::Value, A>
where
A: de::Error,
{
if v.len() != 3 {
Err(de::Error::custom(
"a country tag should be a sequence of 3 letters",
))
} else {
Ok(CountryTag::from(v))
}
}
}
deserializer.deserialize_str(CountryTagVisitor)
}
}