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,
|
12136
|
14 |
consumed: usize,
|
14816
|
15 |
is_recovering: bool,
|
12129
|
16 |
}
|
|
17 |
|
12136
|
18 |
impl ProtocolDecoder {
|
|
19 |
pub fn new() -> ProtocolDecoder {
|
|
20 |
ProtocolDecoder {
|
|
21 |
buf: netbuf::Buf::new(),
|
|
22 |
consumed: 0,
|
14816
|
23 |
is_recovering: false,
|
12129
|
24 |
}
|
|
25 |
}
|
|
26 |
|
14816
|
27 |
fn recover(&mut self) -> bool {
|
|
28 |
self.is_recovering = match parser::malformed_message(&self.buf[..]) {
|
|
29 |
Ok((tail, ())) => {
|
|
30 |
self.buf.consume(self.buf.len() - tail.len());
|
|
31 |
false
|
|
32 |
}
|
|
33 |
_ => {
|
|
34 |
self.buf.consume(self.buf.len());
|
|
35 |
true
|
|
36 |
}
|
|
37 |
};
|
|
38 |
!self.is_recovering
|
|
39 |
}
|
|
40 |
|
12129
|
41 |
pub fn read_from<R: Read>(&mut self, stream: &mut R) -> Result<usize> {
|
14816
|
42 |
let count = self.buf.read_from(stream)?;
|
|
43 |
if count > 0 && self.is_recovering {
|
|
44 |
self.recover();
|
|
45 |
}
|
|
46 |
Ok(count)
|
12129
|
47 |
}
|
|
48 |
|
12136
|
49 |
pub fn extract_messages(&mut self) -> Vec<messages::HWProtocolMessage> {
|
14816
|
50 |
let mut messages = vec![];
|
|
51 |
let mut consumed = 0;
|
|
52 |
if !self.is_recovering {
|
|
53 |
loop {
|
|
54 |
match parser::message(&self.buf[consumed..]) {
|
|
55 |
Ok((tail, message)) => {
|
|
56 |
messages.push(message);
|
|
57 |
consumed += self.buf.len() - tail.len();
|
|
58 |
}
|
|
59 |
Err(nom::Err::Incomplete(_)) => break,
|
|
60 |
Err(nom::Err::Failure(e)) | Err(nom::Err::Error(e)) => {
|
|
61 |
debug!("Invalid message: {:?}", e);
|
|
62 |
self.buf.consume(consumed);
|
|
63 |
consumed = 0;
|
|
64 |
if !self.recover() || self.buf.is_empty() {
|
|
65 |
break;
|
|
66 |
}
|
|
67 |
}
|
|
68 |
}
|
14478
|
69 |
}
|
12136
|
70 |
}
|
14816
|
71 |
self.buf.consume(consumed);
|
|
72 |
messages
|
12129
|
73 |
}
|
|
74 |
}
|