15079
|
1 |
use self::parser::message;
|
14800
|
2 |
use log::*;
|
12134
|
3 |
use netbuf;
|
14780
|
4 |
use nom::{Err, ErrorKind, IResult};
|
14462
|
5 |
use std::io::{Read, Result};
|
12134
|
6 |
|
12141
|
7 |
pub mod messages;
|
14462
|
8 |
mod parser;
|
13801
|
9 |
#[cfg(test)]
|
13421
|
10 |
pub mod test;
|
12134
|
11 |
|
12141
|
12 |
pub struct ProtocolDecoder {
|
12134
|
13 |
buf: netbuf::Buf,
|
14800
|
14 |
is_recovering: bool,
|
12134
|
15 |
}
|
|
16 |
|
12141
|
17 |
impl ProtocolDecoder {
|
|
18 |
pub fn new() -> ProtocolDecoder {
|
|
19 |
ProtocolDecoder {
|
|
20 |
buf: netbuf::Buf::new(),
|
14800
|
21 |
is_recovering: false,
|
12134
|
22 |
}
|
|
23 |
}
|
|
24 |
|
14800
|
25 |
fn recover(&mut self) -> bool {
|
|
26 |
self.is_recovering = match parser::malformed_message(&self.buf[..]) {
|
|
27 |
Ok((tail, ())) => {
|
|
28 |
self.buf.consume(self.buf.len() - tail.len());
|
|
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 |
|
12141
|
47 |
pub fn extract_messages(&mut self) -> Vec<messages::HWProtocolMessage> {
|
14800
|
48 |
let mut messages = vec![];
|
|
49 |
if !self.is_recovering {
|
|
50 |
loop {
|
14801
|
51 |
match parser::message(&self.buf[..]) {
|
14800
|
52 |
Ok((tail, message)) => {
|
|
53 |
messages.push(message);
|
14801
|
54 |
self.buf.consume(self.buf.len() - tail.len());
|
14800
|
55 |
}
|
|
56 |
Err(nom::Err::Incomplete(_)) => break,
|
|
57 |
Err(nom::Err::Failure(e)) | Err(nom::Err::Error(e)) => {
|
|
58 |
debug!("Invalid message: {:?}", e);
|
|
59 |
if !self.recover() || self.buf.is_empty() {
|
|
60 |
break;
|
|
61 |
}
|
|
62 |
}
|
|
63 |
}
|
14462
|
64 |
}
|
12141
|
65 |
}
|
14800
|
66 |
messages
|
12134
|
67 |
}
|
|
68 |
}
|