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
use crate::prelude::*;
use crate::parsing::fields::{Field, fields};
pub fn line(input: &[u8]) -> Res<String> {
let max_idx = std::cmp::min(input.len(), 998);
unsafe {
for i in 0..max_idx {
if !is_text(*input.get_unchecked(i)) {
return Ok((
input.get_unchecked(i..),
String::Reference(input.get_unchecked(..i)),
));
}
}
Ok((
input.get_unchecked(max_idx..),
String::Reference(input.get_unchecked(..max_idx)),
))
}
}
pub fn check_line(input: &[u8]) -> Res<()> {
let max_idx = std::cmp::min(input.len(), 998);
unsafe {
for i in 0..max_idx {
if !is_text(*input.get_unchecked(i)) {
return Ok((input.get_unchecked(i..), ()));
}
}
Ok((input.get_unchecked(max_idx..), ()))
}
}
pub fn body_lines(input: &[u8]) -> Result<Vec<String>, Error> {
if input.is_empty() {
return Ok(Vec::new());
}
let (mut input, ()) = tag(input, b"\r\n")?;
let mut lines = Vec::new();
loop {
let (new_input, new_line) = line(input)?;
match tag(new_input, b"\r\n") {
Ok((new_input, ())) => input = new_input,
Err(e) => {
if new_input.is_empty() {
lines.push(new_line);
break;
} else {
return Err(e);
}
}
}
lines.push(new_line);
}
Ok(lines)
}
pub fn body(input: &[u8]) -> Result<Option<String>, Error> {
if input.is_empty() {
return Ok(None);
}
let (mut new_input, ()) = tag(input, b"\r\n")?;
loop {
let (new_input2, ()) = check_line(new_input)?;
match tag(new_input2, b"\r\n") {
Ok((new_input2, ())) => new_input = new_input2,
Err(e) => {
if new_input2.is_empty() {
break;
} else {
return Err(e);
}
}
}
}
Ok(Some(unsafe {
String::Reference(input.get_unchecked(2..))
}))
}
pub fn parse_message(input: &[u8]) -> Result<(Vec<Field>, Option<String>), Error> {
let (input, fields) = fields(input)?;
let body = body(input)?;
Ok((fields, body))
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_body() {
assert_eq!(
line(b"This is a line\r\nAnd this is a second line")
.unwrap()
.1,
"This is a line"
);
assert_eq!(
body_lines(b"\r\nThis is a line\r\nAnd this is a second line")
.unwrap()
.len(),
2
);
assert_eq!(
body(b"\r\nThis is a line\r\nAnd this is a second line")
.unwrap()
.unwrap(),
"This is a line\r\nAnd this is a second line"
);
}
#[test]
fn test_full_message() {
println!("{:#?}", parse_message(include_bytes!("../../mail.txt")).unwrap());
}
}