15095
|
1 |
use self::parser::message;
|
14816
|
2 |
use log::*;
|
12129
|
3 |
use netbuf;
|
14478
|
4 |
use std::io::{Read, Result};
|
12129
|
5 |
|
12136
|
6 |
pub mod messages;
|
14478
|
7 |
mod parser;
|
13713
|
8 |
#[cfg(test)]
|
13416
|
9 |
pub mod test;
|
12129
|
10 |
|
12136
|
11 |
pub struct ProtocolDecoder {
|
12129
|
12 |
buf: netbuf::Buf,
|
14816
|
13 |
is_recovering: bool,
|
12129
|
14 |
}
|
|
15 |
|
12136
|
16 |
impl ProtocolDecoder {
|
|
17 |
pub fn new() -> ProtocolDecoder {
|
|
18 |
ProtocolDecoder {
|
|
19 |
buf: netbuf::Buf::new(),
|
14816
|
20 |
is_recovering: false,
|
12129
|
21 |
}
|
|
22 |
}
|
|
23 |
|
14816
|
24 |
fn recover(&mut self) -> bool {
|
|
25 |
self.is_recovering = match parser::malformed_message(&self.buf[..]) {
|
|
26 |
Ok((tail, ())) => {
|
15463
|
27 |
let length = tail.len();
|
|
28 |
self.buf.consume(self.buf.len() - length);
|
14816
|
29 |
false
|
|
30 |
}
|
|
31 |
_ => {
|
|
32 |
self.buf.consume(self.buf.len());
|
|
33 |
true
|
|
34 |
}
|
|
35 |
};
|
|
36 |
!self.is_recovering
|
|
37 |
}
|
|
38 |
|
12129
|
39 |
pub fn read_from<R: Read>(&mut self, stream: &mut R) -> Result<usize> {
|
14816
|
40 |
let count = self.buf.read_from(stream)?;
|
|
41 |
if count > 0 && self.is_recovering {
|
|
42 |
self.recover();
|
|
43 |
}
|
|
44 |
Ok(count)
|
12129
|
45 |
}
|
|
46 |
|
15096
|
47 |
pub fn extract_messages(&mut self) -> Vec<messages::HwProtocolMessage> {
|
14816
|
48 |
let mut messages = vec![];
|
|
49 |
if !self.is_recovering {
|
15144
|
50 |
while !self.buf.is_empty() {
|
14817
|
51 |
match parser::message(&self.buf[..]) {
|
14816
|
52 |
Ok((tail, message)) => {
|
|
53 |
messages.push(message);
|
15463
|
54 |
let length = tail.len();
|
|
55 |
self.buf.consume(self.buf.len() - length);
|
14816
|
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 |
}
|
14478
|
65 |
}
|
12136
|
66 |
}
|
14816
|
67 |
messages
|
12129
|
68 |
}
|
|
69 |
}
|