12134
|
1 |
use netbuf;
|
13443
|
2 |
use std::{
|
|
3 |
io::{Read, Result}
|
|
4 |
};
|
|
5 |
use nom::{
|
|
6 |
IResult, Err
|
|
7 |
};
|
12134
|
8 |
|
12141
|
9 |
pub mod messages;
|
13801
|
10 |
#[cfg(test)]
|
13421
|
11 |
pub mod test;
|
12138
|
12 |
mod parser;
|
12134
|
13 |
|
12141
|
14 |
pub struct ProtocolDecoder {
|
12134
|
15 |
buf: netbuf::Buf,
|
12141
|
16 |
consumed: usize,
|
12134
|
17 |
}
|
|
18 |
|
12141
|
19 |
impl ProtocolDecoder {
|
|
20 |
pub fn new() -> ProtocolDecoder {
|
|
21 |
ProtocolDecoder {
|
|
22 |
buf: netbuf::Buf::new(),
|
|
23 |
consumed: 0,
|
12134
|
24 |
}
|
|
25 |
}
|
|
26 |
|
|
27 |
pub fn read_from<R: Read>(&mut self, stream: &mut R) -> Result<usize> {
|
|
28 |
self.buf.read_from(stream)
|
|
29 |
}
|
|
30 |
|
12141
|
31 |
pub fn extract_messages(&mut self) -> Vec<messages::HWProtocolMessage> {
|
|
32 |
let parse_result = parser::extract_messages(&self.buf[..]);
|
|
33 |
match parse_result {
|
13443
|
34 |
Ok((tail, msgs)) => {
|
12141
|
35 |
self.consumed = self.buf.len() - self.consumed - tail.len();
|
|
36 |
msgs
|
|
37 |
},
|
13443
|
38 |
Err(Err::Incomplete(_)) => unreachable!(),
|
|
39 |
Err(Err::Error(_)) | Err(Err::Failure(_)) => unreachable!(),
|
12141
|
40 |
}
|
|
41 |
}
|
|
42 |
|
|
43 |
pub fn sweep(&mut self) {
|
|
44 |
self.buf.consume(self.consumed);
|
|
45 |
self.consumed = 0;
|
12134
|
46 |
}
|
|
47 |
}
|