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