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
pub struct Prefix {
raw: String
}
impl ToString for Prefix {
fn to_string(&self) -> String {
self.raw.to_string()
}
}
impl Prefix {
pub fn new(raw: &str) -> Prefix {
Prefix {
raw: raw.to_string()
}
}
pub fn builder(name: &str) -> PrefixBuilder {
PrefixBuilder {
name,
user: None,
host: None,
}
}
pub fn name(&self) -> &str {
let end = self.raw.find('!')
.or(self.raw.find('@'))
.or(self.raw.find(' '))
.unwrap_or(self.raw.len());
&self.raw[..end]
}
pub fn host(&self) -> Option<&str> {
self.raw.find('@')
.and_then(|index| Some(&self.raw[index + 1..]))
}
pub fn user(&self) -> Option<&str> {
self.raw.find('!')
.and_then(|start| {
let end = self.raw.find('@')
.unwrap_or(self.raw.len());
Some(&self.raw[start + 1..end])
})
}
}
pub struct PrefixBuilder<'a> {
name: &'a str,
user: Option<&'a str>,
host: Option<&'a str>,
}
impl<'a> PrefixBuilder<'a> {
pub fn user(mut self, user: &'a str) -> PrefixBuilder<'a> {
self.user = Some(user);
self
}
pub fn host(mut self, host: &'a str) -> PrefixBuilder<'a> {
self.host = Some(host);
self
}
pub fn build(self) -> Result<Prefix, &'a str> {
if self.user.is_some() && self.host.is_none() {
return Err("user can only be present if host is also present");
}
let mut str = String::from(self.name);
if let Some(user) = self.user {
str.push('!');
str.push_str(&user);
}
if let Some(host) = self.host {
str.push('@');
str.push_str(&host);
}
Ok(Prefix {
raw: str
})
}
}