rumq_core/mqtt4/
codec.rs

1//! This module describes how to serialize and deserialize mqtt 4 packets
2use bytes::buf::Buf;
3use bytes::BytesMut;
4use tokio_util::codec::{Decoder, Encoder};
5
6use std::io;
7use std::io::{Cursor, ErrorKind::TimedOut, ErrorKind::UnexpectedEof, ErrorKind::WouldBlock};
8
9use crate::mqtt4::Packet;
10use crate::mqtt4::{MqttRead, MqttWrite};
11use crate::Error;
12
13/// MqttCodec knows how to serialize and deserialize mqtt packets from a raw stream of bytes
14pub struct MqttCodec {
15    max_payload_size: usize,
16}
17
18impl MqttCodec {
19    pub fn new(max_payload_size: usize) -> Self {
20        MqttCodec { max_payload_size }
21    }
22}
23
24impl Decoder for MqttCodec {
25    type Item = Packet;
26    type Error = Error;
27
28    fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Packet>, Error> {
29        // NOTE: `decode` might be called with `buf.len == 0`. We should return
30        // Ok(None) in those cases or else the internal `read_exact` call will return UnexpectedEOF
31        if buf.len() < 2 {
32            return Ok(None);
33        }
34
35        // TODO: Better implementation by taking packet type and remaining len into account here
36        // Maybe the next `decode` call can wait for publish size byts to be filled in `buf` before being
37        // invoked again
38        // TODO: Find how the underlying implementation invokes this method. Is there an
39        // implementation with size awareness?
40        let mut buf_ref = buf.as_ref();
41        let (packet_type, remaining_len) = match buf_ref.read_packet_type_and_remaining_length() {
42            Ok(len) => len,
43            // Not being able to fill `buf_ref` entirely is also UnexpectedEof
44            // This would be a problem if `buf` len is 2 and if the packet is not ping or other 2
45            // byte len, `read_packet_type_and_remaining_length` call tries reading more than 2 bytes
46            // from `buf` and results in Ok(0) which translates to Eof error when target buffer is
47            // not completely full
48            // https://doc.rust-lang.org/stable/std/io/trait.Read.html#tymethod.read
49            // https://doc.rust-lang.org/stable/src/std/io/mod.rs.html#501-944
50            Err(Error::Io(e)) if e.kind() == TimedOut || e.kind() == WouldBlock || e.kind() == UnexpectedEof => return Ok(None),
51            Err(e) => return Err(e.into()),
52        };
53
54        if remaining_len > self.max_payload_size {
55            return Err(Error::PayloadSizeLimitExceeded);
56        }
57
58        let header_len = buf_ref.header_len(remaining_len);
59        let len = header_len + remaining_len;
60
61        // NOTE: It's possible that `decode` got called before `buf` has full bytes
62        // necessary to frame raw bytes into a packet. In that case return Ok(None)
63        // and the next time decode` gets called, there will be more bytes in `buf`,
64        // hopefully enough to frame the packet
65        if buf.len() < len {
66            return Ok(None);
67        }
68
69        let packet = buf_ref.deserialize(packet_type, remaining_len)?;
70        buf.advance(len);
71        Ok(Some(packet))
72    }
73}
74
75impl Encoder<Packet> for MqttCodec {
76    type Error = io::Error;
77
78    fn encode(&mut self, msg: Packet, buf: &mut BytesMut) -> Result<(), io::Error> {
79        let mut stream = Cursor::new(Vec::new());
80
81        // TODO: Implement `write_packet` for `&mut BytesMut`
82        if let Err(_) = stream.mqtt_write(&msg) {
83            return Err(io::Error::new(io::ErrorKind::Other, "Unable to encode!"));
84        }
85
86        buf.extend(stream.get_ref());
87        Ok(())
88    }
89}