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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
|
use std::str::FromStr;
#[derive(PartialEq, Debug)]
pub struct JID {
// TODO: validate localpart (length, char]
pub localpart: Option<String>,
pub domainpart: String,
pub resourcepart: Option<String>,
}
#[derive(Debug)]
pub enum JIDParseError {
Empty,
Malformed,
}
impl JID {
pub fn new(
localpart: Option<String>,
domainpart: String,
resourcepart: Option<String>,
) -> Self {
Self {
localpart,
domainpart: domainpart.parse().unwrap(),
resourcepart,
}
}
}
impl FromStr for JID {
type Err = JIDParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let split: Vec<&str> = s.split('@').collect();
match split.len() {
0 => Err(JIDParseError::Empty),
1 => {
let split: Vec<&str> = split[0].split('/').collect();
match split.len() {
1 => Ok(JID::new(None, split[0].to_string(), None)),
2 => Ok(JID::new(
None,
split[0].to_string(),
Some(split[1].to_string()),
)),
_ => Err(JIDParseError::Malformed),
}
}
2 => {
let split2: Vec<&str> = split[1].split('/').collect();
match split2.len() {
1 => Ok(JID::new(
Some(split[0].to_string()),
split2[0].to_string(),
None,
)),
2 => Ok(JID::new(
Some(split[0].to_string()),
split2[0].to_string(),
Some(split2[1].to_string()),
)),
_ => Err(JIDParseError::Malformed),
}
}
_ => Err(JIDParseError::Malformed),
}
}
}
impl TryFrom<String> for JID {
type Error = JIDParseError;
fn try_from(value: String) -> Result<Self, Self::Error> {
value.parse()
}
}
impl std::fmt::Display for JID {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}{}{}",
self.localpart.clone().map(|l| l + "@").unwrap_or_default(),
self.domainpart,
self.resourcepart
.clone()
.map(|r| "/".to_owned() + &r)
.unwrap_or_default()
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn jid_to_string() {
assert_eq!(
JID::new(Some("cel".into()), "blos.sm".into(), None).to_string(),
"cel@blos.sm".to_owned()
);
}
#[test]
fn parse_full_jid() {
assert_eq!(
"cel@blos.sm/greenhouse".parse::<JID>().unwrap(),
JID::new(
Some("cel".into()),
"blos.sm".into(),
Some("greenhouse".into())
)
)
}
#[test]
fn parse_bare_jid() {
assert_eq!(
"cel@blos.sm".parse::<JID>().unwrap(),
JID::new(Some("cel".into()), "blos.sm".into(), None)
)
}
#[test]
fn parse_domain_jid() {
assert_eq!(
"component.blos.sm".parse::<JID>().unwrap(),
JID::new(None, "component.blos.sm".into(), None)
)
}
#[test]
fn parse_full_domain_jid() {
assert_eq!(
"component.blos.sm/bot".parse::<JID>().unwrap(),
JID::new(None, "component.blos.sm".into(), Some("bot".into()))
)
}
}
|