This repository has been archived by the owner on Jul 31, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
request.rs
101 lines (84 loc) · 2.05 KB
/
request.rs
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
// Use the stuff we need to
use std::io;
use bytes::BytesMut;
/// The result of an incoming request
pub struct Request {
first: BytesMut,
head: BytesMut,
body: BytesMut,
}
impl Request {
/// Get raw body
pub fn body(&self) -> &BytesMut {
&self.body
}
/// Get first line
pub fn first(&self) -> &BytesMut {
&self.first
}
/// Get head
pub fn head(&self) -> &BytesMut {
&self.head
}
}
/// Decode the given raw HTTP request
pub fn decode(buf: &mut BytesMut) -> io::Result<Option<Request>> {
if buf.is_empty() {
return Ok(None);
}
// Clone buffer for iter
let iter = buf.clone();
// Loop over bytes, to find line endings
let mut it = iter.iter();
let mut firstc : u16 = 0_u16;
let mut headc : u16 = 0_u16;
loop {
// Check if end is reached
match it.next() {
Some(&b'\n') => break,
None => break,
_ => {
firstc += 1;
}
};
}
// Cache headers line length
let mut linec : u16 = 0_u16;
loop {
// Check if end of headers reached
match it.next() {
// On line end
Some(&b'\n') => {
// Headers end reached
if linec == 1 {
break;
}
// Increment total length
headc += 1;
// Reset line length
linec = 0;
},
// Buffer end
None => break,
_ => {
// Else increment length
linec += 1;
headc += 1;
}
};
}
// Split buffers into parts
let first = buf.split_to(firstc as usize);
let head = buf.split_to(headc as usize);
let body = buf.clone();
// Clear buffer for next request
buf.clear();
// Build request object
let request = Request {
first: first,
head: head,
body: body,
};
// Create a new Request object
Ok(request.into())
}