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, ())) => {
|
|
27 |
self.buf.consume(self.buf.len() - tail.len());
|
|
28 |
false
|
|
29 |
}
|
|
30 |
_ => {
|
|
31 |
self.buf.consume(self.buf.len());
|
|
32 |
true
|
|
33 |
}
|
|
34 |
};
|
|
35 |
!self.is_recovering
|
|
36 |
}
|
|
37 |
|
12134
|
38 |
pub fn read_from<R: Read>(&mut self, stream: &mut R) -> Result<usize> {
|
14800
|
39 |
let count = self.buf.read_from(stream)?;
|
|
40 |
if count > 0 && self.is_recovering {
|
|
41 |
self.recover();
|
|
42 |
}
|
|
43 |
Ok(count)
|
12134
|
44 |
}
|
|
45 |
|
15080
|
46 |
pub fn extract_messages(&mut self) -> Vec<messages::HwProtocolMessage> {
|
14800
|
47 |
let mut messages = vec![];
|
|
48 |
if !self.is_recovering {
|
15128
|
49 |
while !self.buf.is_empty() {
|
14801
|
50 |
match parser::message(&self.buf[..]) {
|
14800
|
51 |
Ok((tail, message)) => {
|
|
52 |
messages.push(message);
|
14801
|
53 |
self.buf.consume(self.buf.len() - tail.len());
|
14800
|
54 |
}
|
|
55 |
Err(nom::Err::Incomplete(_)) => break,
|
|
56 |
Err(nom::Err::Failure(e)) | Err(nom::Err::Error(e)) => {
|
|
57 |
debug!("Invalid message: {:?}", e);
|
|
58 |
if !self.recover() || self.buf.is_empty() {
|
|
59 |
break;
|
|
60 |
}
|
|
61 |
}
|
|
62 |
}
|
14462
|
63 |
}
|
12141
|
64 |
}
|
14800
|
65 |
messages
|
12134
|
66 |
}
|
|
67 |
}
|