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
#[derive(PartialEq)]
#[derive(Debug)]
pub struct Pair {
pub key: String,
pub val: Option<String>,
}
fn complete_pair(buf: String, pair: Option<Pair>) -> Pair {
match pair {
Some(Pair { key: k, val: _ }) =>
Pair { key: k, val: Some(buf) },
None =>
Pair { key: buf, val: None },
}
}
pub fn parse(message: &str) -> Vec<Pair> {
let mut pair: Option<Pair> = None;
let mut pairs: Vec<Pair> = vec![];
let mut buf = String::new();
let mut escape = false;
let mut garbage = false;
let mut quoted = false;
for c in message.chars() {
match (quoted, c) {
(false, ' ') => {
if !buf.is_empty() {
if !garbage {
pairs.push(complete_pair(buf, pair));
pair = None;
}
buf = String::new();
}
garbage = false;
},
(false, '=') => {
if !buf.is_empty() {
pair = Some(Pair{key: buf, val: None});
buf = String::new();
} else {
garbage = true;
}
},
(true, '\\') => {
escape = true;
}
(_, '"') => {
if escape {
buf.push(c);
escape = false;
} else {
quoted = !quoted;
}
},
_ => {
if escape {
buf.push('\\');
escape = false;
}
buf.push(c);
},
}
}
if !garbage {
pairs.push(complete_pair(buf, pair));
}
pairs
}