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
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
use crate::{
    BinaryData, Bits, Error, FourByteInteger, Result as SageResult, TwoByteInteger, UTF8String,
    VariableByteInteger,
};
use std::io::{Cursor, Error as IOError, ErrorKind, Write};
use unicode_reader::CodePoints;

/// The `Encode` trait describes how to write a type into an MQTT stream.
pub trait Encode {
    /// Encodes `this` and writes it into `write`, returning how many bytes
    /// were written.
    fn encode<W: Write>(&self, writer: &mut W) -> SageResult<usize>;
}

impl Encode for Bits {
    fn encode<W: Write>(&self, writer: &mut W) -> SageResult<usize> {
        Ok(writer.write(&[self.0])?)
    }
}

impl Encode for TwoByteInteger {
    fn encode<W: Write>(&self, writer: &mut W) -> SageResult<usize> {
        Ok(writer.write(&self.0.to_be_bytes())?)
    }
}

impl Encode for FourByteInteger {
    fn encode<W: Write>(&self, writer: &mut W) -> SageResult<usize> {
        Ok(writer.write(&self.0.to_be_bytes())?)
    }
}

impl Encode for UTF8String {
    fn encode<W>(&self, writer: &mut W) -> SageResult<usize>
    where
        W: Write,
    {
        let mut codepoints = CodePoints::from(Cursor::new(&self.0));
        if codepoints.all(|x| match x {
            Ok('\u{0}') => false,
            Ok(_) => true,
            _ => false, // Will be an IO Error
        }) {
            let data = &self.0;
            let len = data.len();
            if len > i16::max_value() as usize {
                return Err(Error::MalformedPacket);
            }
            writer.write_all(&(len as u16).to_be_bytes())?;
            writer.write_all(data)?;
            Ok(2 + len)
        } else {
            Err(Error::MalformedPacket)
        }
    }
}

impl Encode for VariableByteInteger {
    fn encode<W>(&self, writer: &mut W) -> SageResult<usize>
    where
        W: Write,
    {
        let bytes = match self {
            VariableByteInteger::One(b0) => writer.write(&[*b0])?,
            VariableByteInteger::Two(b1, b0) => writer.write(&[*b1, *b0])?,
            VariableByteInteger::Three(b2, b1, b0) => writer.write(&[*b2, *b1, *b0])?,
            VariableByteInteger::Four(b3, b2, b1, b0) => writer.write(&[*b3, *b2, *b1, *b0])?,
        };
        Ok(bytes)
    }
}

impl Encode for BinaryData {
    fn encode<W>(&self, writer: &mut W) -> SageResult<usize>
    where
        W: Write,
    {
        let data = &self.0;
        let len = data.len();
        if len > i16::max_value() as usize {
            return Err(IOError::new(ErrorKind::InvalidData, "ERROR_MSG_DATA_TOO_LONG").into());
        }
        writer.write_all(&(len as u16).to_be_bytes())?;
        writer.write_all(data)?;
        Ok(2 + len)
    }
}

#[cfg(test)]
mod unit_encode {

    use super::*;

    #[test]
    fn encode_bits() {
        let input = Bits(0b00101010);
        let mut result = Vec::new();
        let expected = vec![0x2A];
        let bytes = input.encode(&mut result).unwrap();
        assert_eq!(bytes, 1);
        assert_eq!(result, expected, "Encoding {:?} failed", input);
    }

    #[test]
    fn encode_two_byte_integer() {
        let input = TwoByteInteger(1984u16);
        let mut result = Vec::new();
        let expected = vec![0x07, 0xC0];
        let bytes = input.encode(&mut result).unwrap();
        assert_eq!(bytes, 2);
        assert_eq!(result, expected, "Encoding {:?} failed", input);
    }

    #[test]
    fn encode_four_byte_integer() {
        let input = FourByteInteger(220_000_u32);
        let mut result = Vec::new();
        let expected = vec![0x00, 0x03, 0x5B, 0x60];
        let bytes = input.encode(&mut result).unwrap();
        assert_eq!(bytes, 4);
        assert_eq!(result, expected, "Encoding {:?} failed", input);
    }

    #[test]
    fn encode_utf8string() {
        let input = UTF8String(Vec::from("A𪛔".as_bytes()));
        let mut result = Vec::new();
        let expected = vec![0x00, 0x05, 0x41, 0xF0, 0xAA, 0x9B, 0x94];
        let bytes = input.encode(&mut result).unwrap();
        assert_eq!(bytes, 7);
        assert_eq!(result, expected, "Encoding {:?} failed", input);
    }

    #[test]
    fn encode_utf8string_empty() {
        let input = UTF8String(Vec::new());
        let mut result = Vec::new();
        let expected = vec![0x00, 0x00];
        let bytes = input.encode(&mut result).unwrap();
        assert_eq!(bytes, 2);
        assert_eq!(result, expected, "Encoding {:?} failed", input);
    }

    // The character data in a UTF-8 Encoded String MUST be well-formed UTF-8 as
    // defined by the Unicode specification [Unicode] and restated in
    // RFC 3629 [RFC3629]. In particular, the character data MUST NOT include
    // encodings of code points between U+D800 and U+DFFF [MQTT-1.5.4-1]
    #[test]
    fn encode_conformance_mqtt_1_5_4_1() {
        let input = UTF8String(vec![0xD8, 0x00]);
        let mut test_stream = Vec::new();
        assert_matches!(input.encode(&mut test_stream), Err(Error::MalformedPacket));
        assert_eq!(test_stream.len(), 0);
    }

    /// A UTF-8 Encoded String MUST NOT include an encoding of the null
    /// character U+0000
    #[test]
    fn encode_conformance_mqtt_1_5_4_2() {
        let input = UTF8String(vec![0x00, 0x00]);
        let mut test_stream = Vec::new();
        assert_matches!(input.encode(&mut test_stream), Err(Error::MalformedPacket));
        assert_eq!(test_stream.len(), 0);
    }

    #[test]
    fn encode_variable_byte_integer_one_lower_bound() {
        let input = VariableByteInteger::One(0_u8);
        let mut result = Vec::new();
        let expected = vec![0x00];
        let bytes = input.encode(&mut result).unwrap();
        assert_eq!(bytes, 1);
        assert_eq!(result, expected, "Encoding {:?} failed", input);
    }

    #[test]
    fn encode_variable_byte_integer_one_upper_bound() {
        let input = VariableByteInteger::One(127_u8);
        let mut result = Vec::new();
        let expected = vec![0x7F];
        let bytes = input.encode(&mut result).unwrap();
        assert_eq!(bytes, 1);
        assert_eq!(result, expected, "Encoding {:?} failed", input);
    }

    #[test]
    fn encode_variable_byte_integer_two_lower_bound() {
        let input = VariableByteInteger::Two(128_u8, 01_u8);
        let mut result = Vec::new();
        let expected = vec![0x80, 0x01];
        let bytes = input.encode(&mut result).unwrap();
        assert_eq!(bytes, 2);
        assert_eq!(result, expected, "Encoding {:?} failed", input);
    }

    #[test]
    fn encode_variable_byte_integer_two_upper_bound() {
        let input = VariableByteInteger::Two(255_u8, 127_u8);
        let mut result = Vec::new();
        let expected = vec![0xFF, 0x7F];
        let bytes = input.encode(&mut result).unwrap();
        assert_eq!(bytes, 2);
        assert_eq!(result, expected, "Encoding {:?} failed", input);
    }

    #[test]
    fn encode_variable_byte_integer_three_lower_bound() {
        let input = VariableByteInteger::Three(128_u8, 128_u8, 01_u8);
        let mut result = Vec::new();
        let expected = vec![0x80, 0x80, 0x01];
        let bytes = input.encode(&mut result).unwrap();
        assert_eq!(bytes, 3);
        assert_eq!(result, expected, "Encoding {:?} failed", input);
    }

    #[test]
    fn encode_variable_byte_integer_three_upper_bound() {
        let input = VariableByteInteger::Three(255_u8, 255_u8, 127_u8);
        let mut result = Vec::new();
        let expected = vec![0xFF, 0xFF, 0x7F];
        let bytes = input.encode(&mut result).unwrap();
        assert_eq!(bytes, 3);
        assert_eq!(result, expected, "Encoding {:?} failed", input);
    }

    #[test]
    fn encode_variable_byte_integer_four_lower_bound() {
        let input = VariableByteInteger::Four(128_u8, 128_u8, 128_u8, 01_u8);
        let mut result = Vec::new();
        let expected = vec![0x80, 0x80, 0x80, 0x01];
        let bytes = input.encode(&mut result).unwrap();
        assert_eq!(bytes, 4);
        assert_eq!(result, expected, "Encoding {:?} failed", input);
    }

    #[test]
    fn encode_variable_byte_integer_four_upper_bound() {
        let input = VariableByteInteger::Four(255_u8, 255_u8, 255_u8, 127_u8);
        let mut result = Vec::new();
        let expected = vec![0xFF, 0xFF, 0xFF, 0x7F];
        let bytes = input.encode(&mut result).unwrap();
        assert_eq!(bytes, 4);
        assert_eq!(result, expected, "Encoding {:?} failed", input);
    }

    #[test]
    fn encode_binarydata() {
        let input = BinaryData(Vec::from("A𪛔".as_bytes()));
        let mut result = Vec::new();
        let expected = vec![0x00, 0x05, 0x41, 0xF0, 0xAA, 0x9B, 0x94];
        let bytes = input.encode(&mut result).unwrap();
        assert_eq!(bytes, 7);
        assert_eq!(result, expected, "Encoding {:?} failed", input);
    }

    #[test]
    fn encode_binarydata_empty() {
        let input = BinaryData(Vec::new());
        let mut result = Vec::new();
        let expected = vec![0x00, 0x00];
        let bytes = input.encode(&mut result).unwrap();
        assert_eq!(bytes, 2);
        assert_eq!(result, expected, "Encoding {:?} failed", input);
    }
}