1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use bytes::BytesMut;
use mqtt311::{self, MqttRead, MqttWrite, Packet};
use std::io::{self, Cursor, ErrorKind};
use tokio_codec::{Decoder, Encoder};
#[derive(Debug)]
pub struct MqttCodec;
impl Decoder for MqttCodec {
type Item = Packet;
type Error = io::Error;
fn decode(&mut self, buf: &mut BytesMut) -> io::Result<Option<Packet>> {
if buf.len() < 2 {
return Ok(None);
}
let (packet, len) = {
let mut buf_ref = buf.as_ref();
match buf_ref.read_packet_with_len() {
Err(e) => {
if let mqtt311::Error::Io(e) = e {
match e.kind() {
ErrorKind::TimedOut | ErrorKind::WouldBlock | ErrorKind::UnexpectedEof => return Ok(None),
_ => {
error!("mqtt3 io error = {:?}", e);
return Err(e);
}
}
} else {
error!("mqtt3 read error = {:?}", e);
return Err(io::Error::new(ErrorKind::Other, "Mqtt Error"));
}
}
Ok(v) => v,
}
};
if buf.len() < len {
return Ok(None);
}
buf.split_to(len);
Ok(Some(packet))
}
}
impl Encoder for MqttCodec {
type Item = Packet;
type Error = io::Error;
fn encode(&mut self, msg: Packet, buf: &mut BytesMut) -> io::Result<()> {
let mut stream = Cursor::new(Vec::new());
if let Err(e) = stream.write_packet(&msg) {
error!("Encode error. Error = {:?}", e);
return Err(io::Error::new(io::ErrorKind::Other, "Unable to encode!"));
}
buf.extend(stream.get_ref());
Ok(())
}
}