15074
|
1 |
use self::parser::message;
|
14795
|
2 |
use log::*;
|
12129
|
3 |
use netbuf;
|
14775
|
4 |
use nom::{Err, ErrorKind, IResult};
|
14457
|
5 |
use std::io::{Read, Result};
|
12129
|
6 |
|
12136
|
7 |
pub mod messages;
|
14457
|
8 |
mod parser;
|
13796
|
9 |
#[cfg(test)]
|
13416
|
10 |
pub mod test;
|
12129
|
11 |
|
12136
|
12 |
pub struct ProtocolDecoder {
|
12129
|
13 |
buf: netbuf::Buf,
|
14795
|
14 |
is_recovering: bool,
|
12129
|
15 |
}
|
|
16 |
|
12136
|
17 |
impl ProtocolDecoder {
|
|
18 |
pub fn new() -> ProtocolDecoder {
|
|
19 |
ProtocolDecoder {
|
|
20 |
buf: netbuf::Buf::new(),
|
14795
|
21 |
is_recovering: false,
|
12129
|
22 |
}
|
|
23 |
}
|
|
24 |
|
14795
|
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 |
|
12129
|
39 |
pub fn read_from<R: Read>(&mut self, stream: &mut R) -> Result<usize> {
|
14795
|
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 |
|
15075
|
47 |
pub fn extract_messages(&mut self) -> Vec<messages::HwProtocolMessage> {
|
14795
|
48 |
let mut messages = vec![];
|
|
49 |
if !self.is_recovering {
|
|
50 |
loop {
|
14796
|
51 |
match parser::message(&self.buf[..]) {
|
14795
|
52 |
Ok((tail, message)) => {
|
|
53 |
messages.push(message);
|
14796
|
54 |
self.buf.consume(self.buf.len() - tail.len());
|
14795
|
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 |
}
|
14457
|
64 |
}
|
12136
|
65 |
}
|
14795
|
66 |
messages
|
12129
|
67 |
}
|
|
68 |
}
|