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
use crate::{parsers::message::MessageStream, HeaderValue};
pub fn parse_id<'x>(stream: &mut MessageStream<'x>) -> HeaderValue<'x> {
let mut token_start: usize = 0;
let mut token_end: usize = 0;
let mut is_id_part = false;
let mut ids = Vec::new();
let mut iter = stream.data[stream.pos..].iter();
while let Some(ch) = iter.next() {
stream.pos += 1;
match ch {
b'\n' => match stream.data.get(stream.pos) {
Some(b' ' | b'\t') => {
iter.next();
stream.pos += 1;
continue;
}
_ => {
return match ids.len() {
1 => HeaderValue::Text(ids.pop().unwrap()),
0 => HeaderValue::Empty,
_ => HeaderValue::TextList(ids),
};
}
},
b'<' => {
is_id_part = true;
continue;
}
b'>' => {
is_id_part = false;
if token_start > 0 {
ids.push(String::from_utf8_lossy(
&stream.data[token_start - 1..token_end],
));
token_start = 0;
} else {
continue;
}
}
b' ' | b'\t' | b'\r' => continue,
_ => (),
}
if is_id_part {
if token_start == 0 {
token_start = stream.pos;
}
token_end = stream.pos;
}
}
HeaderValue::Empty
}
#[cfg(test)]
mod tests {
use crate::parsers::fields::id::parse_id;
use crate::parsers::message::MessageStream;
use crate::HeaderValue;
#[test]
fn parse_message_ids() {
let inputs = [
(
"<1234@local.machine.example>\n",
vec!["1234@local.machine.example"],
),
(
"<1234@local.machine.example> <3456@example.net>\n",
vec!["1234@local.machine.example", "3456@example.net"],
),
(
"<1234@local.machine.example>\n <3456@example.net> \n",
vec!["1234@local.machine.example", "3456@example.net"],
),
(
"<1234@local.machine.example>\n\n <3456@example.net>\n",
vec!["1234@local.machine.example"],
),
(
" <testabcd.1234@silly.test> \n",
vec!["testabcd.1234@silly.test"],
),
(
"<5678.21-Nov-1997@example.com>\n",
vec!["5678.21-Nov-1997@example.com"],
),
(
"<1234 @ local(blah) .machine .example>\n",
vec!["1234 @ local(blah) .machine .example"],
),
];
for input in inputs {
let str = input.0.to_string();
match parse_id(&mut MessageStream::new(str.as_bytes())) {
HeaderValue::TextList(ids) => {
assert_eq!(ids, input.1, "Failed to parse '{:?}'", input.0);
}
HeaderValue::Text(id) => {
assert!(input.1.len() == 1, "Failed to parse '{:?}'", input.0);
assert_eq!(id, input.1[0], "Failed to parse '{:?}'", input.0);
}
_ => panic!("Unexpected result"),
}
}
}
}