15831
|
1 |
use bytes::{Buf, BufMut, BytesMut};
|
|
2 |
use log::*;
|
|
3 |
use std::{io, io::ErrorKind, marker::Unpin};
|
|
4 |
use tokio::io::AsyncReadExt;
|
|
5 |
|
15804
|
6 |
use hedgewars_network_protocol::{
|
|
7 |
messages::HwProtocolMessage,
|
|
8 |
parser::{malformed_message, message},
|
|
9 |
};
|
12129
|
10 |
|
12136
|
11 |
pub struct ProtocolDecoder {
|
15831
|
12 |
buffer: BytesMut,
|
14795
|
13 |
is_recovering: bool,
|
12129
|
14 |
}
|
|
15 |
|
12136
|
16 |
impl ProtocolDecoder {
|
|
17 |
pub fn new() -> ProtocolDecoder {
|
|
18 |
ProtocolDecoder {
|
15831
|
19 |
buffer: BytesMut::with_capacity(1024),
|
14795
|
20 |
is_recovering: false,
|
12129
|
21 |
}
|
|
22 |
}
|
|
23 |
|
14795
|
24 |
fn recover(&mut self) -> bool {
|
15831
|
25 |
self.is_recovering = match malformed_message(&self.buffer[..]) {
|
14795
|
26 |
Ok((tail, ())) => {
|
15831
|
27 |
let remaining = tail.len();
|
|
28 |
self.buffer.advance(self.buffer.len() - remaining);
|
14795
|
29 |
false
|
|
30 |
}
|
|
31 |
_ => {
|
15831
|
32 |
self.buffer.clear();
|
14795
|
33 |
true
|
|
34 |
}
|
|
35 |
};
|
|
36 |
!self.is_recovering
|
|
37 |
}
|
|
38 |
|
15831
|
39 |
fn extract_message(&mut self) -> Option<HwProtocolMessage> {
|
|
40 |
if !self.is_recovering || self.recover() {
|
|
41 |
match message(&self.buffer[..]) {
|
|
42 |
Ok((tail, message)) => {
|
|
43 |
let remaining = tail.len();
|
|
44 |
self.buffer.advance(self.buffer.len() - remaining);
|
|
45 |
return Some(message);
|
|
46 |
}
|
|
47 |
Err(nom::Err::Incomplete(_)) => {}
|
|
48 |
Err(nom::Err::Failure(e) | nom::Err::Error(e)) => {
|
|
49 |
debug!("Invalid message: {:?}", e);
|
|
50 |
self.recover();
|
14795
|
51 |
}
|
14457
|
52 |
}
|
12136
|
53 |
}
|
15831
|
54 |
None
|
|
55 |
}
|
|
56 |
|
|
57 |
pub async fn read_from<R: AsyncReadExt + Unpin>(
|
|
58 |
&mut self,
|
|
59 |
stream: &mut R,
|
|
60 |
) -> Option<HwProtocolMessage> {
|
|
61 |
loop {
|
|
62 |
if !self.buffer.has_remaining() {
|
|
63 |
let count = stream.read_buf(&mut self.buffer).await.ok()?;
|
|
64 |
if count == 0 {
|
|
65 |
return None;
|
|
66 |
}
|
|
67 |
}
|
|
68 |
while !self.buffer.is_empty() {
|
|
69 |
if let Some(result) = self.extract_message() {
|
|
70 |
return Some(result);
|
|
71 |
}
|
|
72 |
}
|
|
73 |
}
|
12129
|
74 |
}
|
|
75 |
}
|