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, ())) => {
|
|
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 |
|
12129
|
38 |
pub fn read_from<R: Read>(&mut self, stream: &mut R) -> Result<usize> {
|
14816
|
39 |
let count = self.buf.read_from(stream)?;
|
|
40 |
if count > 0 && self.is_recovering {
|
|
41 |
self.recover();
|
|
42 |
}
|
|
43 |
Ok(count)
|
12129
|
44 |
}
|
|
45 |
|
15096
|
46 |
pub fn extract_messages(&mut self) -> Vec<messages::HwProtocolMessage> {
|
14816
|
47 |
let mut messages = vec![];
|
|
48 |
if !self.is_recovering {
|
|
49 |
loop {
|
14817
|
50 |
match parser::message(&self.buf[..]) {
|
14816
|
51 |
Ok((tail, message)) => {
|
|
52 |
messages.push(message);
|
14817
|
53 |
self.buf.consume(self.buf.len() - tail.len());
|
14816
|
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 |
}
|
14478
|
63 |
}
|
12136
|
64 |
}
|
14816
|
65 |
messages
|
12129
|
66 |
}
|
|
67 |
}
|