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