15079
|
1 |
use self::parser::message;
|
14800
|
2 |
use log::*;
|
12134
|
3 |
use netbuf;
|
14462
|
4 |
use std::io::{Read, Result};
|
12134
|
5 |
|
12141
|
6 |
pub mod messages;
|
14462
|
7 |
mod parser;
|
13801
|
8 |
#[cfg(test)]
|
13421
|
9 |
pub mod test;
|
12134
|
10 |
|
12141
|
11 |
pub struct ProtocolDecoder {
|
12134
|
12 |
buf: netbuf::Buf,
|
14800
|
13 |
is_recovering: bool,
|
12134
|
14 |
}
|
|
15 |
|
12141
|
16 |
impl ProtocolDecoder {
|
|
17 |
pub fn new() -> ProtocolDecoder {
|
|
18 |
ProtocolDecoder {
|
|
19 |
buf: netbuf::Buf::new(),
|
14800
|
20 |
is_recovering: false,
|
12134
|
21 |
}
|
|
22 |
}
|
|
23 |
|
14800
|
24 |
fn recover(&mut self) -> bool {
|
|
25 |
self.is_recovering = match parser::malformed_message(&self.buf[..]) {
|
|
26 |
Ok((tail, ())) => {
|
15444
|
27 |
let length = tail.len();
|
|
28 |
self.buf.consume(self.buf.len() - length);
|
14800
|
29 |
false
|
|
30 |
}
|
|
31 |
_ => {
|
|
32 |
self.buf.consume(self.buf.len());
|
|
33 |
true
|
|
34 |
}
|
|
35 |
};
|
|
36 |
!self.is_recovering
|
|
37 |
}
|
|
38 |
|
12134
|
39 |
pub fn read_from<R: Read>(&mut self, stream: &mut R) -> Result<usize> {
|
14800
|
40 |
let count = self.buf.read_from(stream)?;
|
|
41 |
if count > 0 && self.is_recovering {
|
|
42 |
self.recover();
|
|
43 |
}
|
|
44 |
Ok(count)
|
12134
|
45 |
}
|
|
46 |
|
15080
|
47 |
pub fn extract_messages(&mut self) -> Vec<messages::HwProtocolMessage> {
|
14800
|
48 |
let mut messages = vec![];
|
|
49 |
if !self.is_recovering {
|
15128
|
50 |
while !self.buf.is_empty() {
|
14801
|
51 |
match parser::message(&self.buf[..]) {
|
14800
|
52 |
Ok((tail, message)) => {
|
|
53 |
messages.push(message);
|
15444
|
54 |
let length = tail.len();
|
|
55 |
self.buf.consume(self.buf.len() - length);
|
14800
|
56 |
}
|
|
57 |
Err(nom::Err::Incomplete(_)) => break,
|
|
58 |
Err(nom::Err::Failure(e)) | Err(nom::Err::Error(e)) => {
|
|
59 |
debug!("Invalid message: {:?}", e);
|
|
60 |
if !self.recover() || self.buf.is_empty() {
|
|
61 |
break;
|
|
62 |
}
|
|
63 |
}
|
|
64 |
}
|
14462
|
65 |
}
|
12141
|
66 |
}
|
14800
|
67 |
messages
|
12134
|
68 |
}
|
|
69 |
}
|