symqtt-codec 0.1.0

MQTT 3.1.1/5.0 packet codec — role-neutral, runtime-free
Documentation
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! MQTT primitive data type read/write helpers
//!
//! Implements the four fundamental data representations defined in
//! [MQTT-1.5]: single byte, two-byte integer (big-endian), UTF-8 encoded
//! string (length-prefixed), and binary data (length-prefixed).

use bytes::{Buf, BufMut, Bytes, BytesMut};

use crate::{DecodeError, EncodeError};

/// Byte count of the length prefix carried by strings and binary data [MQTT-1.5.3, MQTT-1.5.6]
pub const LEN_PREFIX: usize = 2;

/// Encoded byte size of a Packet Identifier [MQTT-2.3.1]
pub const PACKET_ID_LEN: usize = 2;

/// Largest payload a length-prefixed string or binary field can hold [MQTT-1.5.3]
pub const MAX_PREFIXED_LEN: usize = u16::MAX as usize;

/// Read a single byte from the buffer
///
/// # Errors
///
/// Returns [`DecodeError::InsufficientBytes`] if the buffer is empty
pub fn read_u8(buf: &mut Bytes) -> Result<u8, DecodeError> {
    if buf.remaining() < 1 {
        return Err(DecodeError::InsufficientBytes { needed: 1 });
    }
    Ok(buf.get_u8())
}

/// Write a single byte to the buffer
pub fn write_u8(value: u8, buf: &mut BytesMut) {
    buf.put_u8(value);
}

/// Read a two-byte big-endian unsigned integer [MQTT-1.5.2]
///
/// # Errors
///
/// Returns [`DecodeError::InsufficientBytes`] if fewer than two bytes remain
pub fn read_u16(buf: &mut Bytes) -> Result<u16, DecodeError> {
    if buf.remaining() < 2 {
        return Err(DecodeError::InsufficientBytes { needed: 2 });
    }
    Ok(buf.get_u16())
}

/// Write a two-byte big-endian unsigned integer [MQTT-1.5.2]
pub fn write_u16(value: u16, buf: &mut BytesMut) {
    buf.put_u16(value);
}

/// Read a four-byte big-endian unsigned integer [MQTTv5-1.5.3]
///
/// # Errors
///
/// Returns [`DecodeError::InsufficientBytes`] if fewer than four bytes remain
pub fn read_u32(buf: &mut Bytes) -> Result<u32, DecodeError> {
    if buf.remaining() < 4 {
        return Err(DecodeError::InsufficientBytes { needed: 4 });
    }
    Ok(buf.get_u32())
}

/// Write a four-byte big-endian unsigned integer [MQTTv5-1.5.3]
pub fn write_u32(value: u32, buf: &mut BytesMut) {
    buf.put_u32(value);
}

/// Read a UTF-8 encoded string with a two-byte length prefix [MQTT-1.5.3]
///
/// # Errors
///
/// Returns [`DecodeError::InsufficientBytes`] if the prefix or the announced
/// number of content bytes is missing
///
/// Returns [`DecodeError::InvalidUtf8`] if the content is not well-formed UTF-8
/// [MQTT-1.5.3-1] or contains the null character U+0000 [MQTT-1.5.3-2]
pub fn read_string(buf: &mut Bytes) -> Result<String, DecodeError> {
    let data = read_binary(buf)?;
    let s = std::str::from_utf8(&data).map_err(|_| DecodeError::InvalidUtf8 {
        reason: "invalid utf-8 sequence",
    })?;
    if s.contains('\0') {
        return Err(DecodeError::InvalidUtf8 {
            reason: "contains null character U+0000",
        });
    }
    Ok(s.to_owned())
}

/// Write a UTF-8 encoded string with a two-byte length prefix [MQTT-1.5.3]
///
/// # Errors
///
/// Returns [`EncodeError::StringTooLong`] if the string exceeds
/// [`MAX_PREFIXED_LEN`] bytes, which the length prefix cannot express
///
/// Returns [`EncodeError::StringContainsNull`] if it contains U+0000,
/// forbidden by [MQTT-1.5.3-2]
pub fn write_string(s: &str, buf: &mut BytesMut) -> Result<(), EncodeError> {
    if s.contains('\0') {
        return Err(EncodeError::StringContainsNull);
    }
    write_binary(s.as_bytes(), buf)
}

/// Read binary data with a two-byte length prefix [MQTT-1.5.6]
///
/// # Errors
///
/// Returns [`DecodeError::InsufficientBytes`] if the prefix or the announced
/// number of content bytes is missing
pub fn read_binary(buf: &mut Bytes) -> Result<Bytes, DecodeError> {
    let len = read_u16(buf)? as usize;
    if buf.remaining() < len {
        return Err(DecodeError::InsufficientBytes {
            needed: len - buf.remaining(),
        });
    }
    Ok(buf.split_to(len))
}

/// Write binary data with a two-byte length prefix [MQTT-1.5.6]
///
/// # Errors
///
/// Returns [`EncodeError::StringTooLong`] if the data exceeds
/// [`MAX_PREFIXED_LEN`] bytes, which the length prefix cannot express
pub fn write_binary(data: &[u8], buf: &mut BytesMut) -> Result<(), EncodeError> {
    let len = data.len();
    if len > MAX_PREFIXED_LEN {
        return Err(EncodeError::StringTooLong { len });
    }
    buf.reserve(LEN_PREFIX + len);
    buf.put_u16(len as u16);
    buf.extend_from_slice(data);
    Ok(())
}

/// Read a UTF-8 string pair (name + value) [MQTTv5-1.5.7]
///
/// # Errors
///
/// Returns [`DecodeError::InsufficientBytes`] or [`DecodeError::InvalidUtf8`]
/// propagated from the underlying string reads
pub fn read_string_pair(buf: &mut Bytes) -> Result<(String, String), DecodeError> {
    let name = read_string(buf)?;
    let value = read_string(buf)?;
    Ok((name, value))
}

/// Write a UTF-8 string pair [MQTTv5-1.5.7]
///
/// # Errors
///
/// Returns [`EncodeError::StringTooLong`] or [`EncodeError::StringContainsNull`]
/// if either string violates constraints
pub fn write_string_pair(name: &str, value: &str, buf: &mut BytesMut) -> Result<(), EncodeError> {
    write_string(name, buf)?;
    write_string(value, buf)?;
    Ok(())
}

/// Encoded byte length of a length-prefixed string (2-byte prefix + content)
#[inline]
pub const fn string_encoded_len(s_len: usize) -> usize {
    LEN_PREFIX + s_len
}

/// Encoded byte length of a length-prefixed binary field (2-byte prefix + content)
#[inline]
pub const fn binary_encoded_len(data_len: usize) -> usize {
    LEN_PREFIX + data_len
}

/// Encoded byte length of a string pair (two length-prefixed strings)
#[inline]
pub const fn string_pair_encoded_len(name_len: usize, value_len: usize) -> usize {
    LEN_PREFIX + name_len + LEN_PREFIX + value_len
}

#[cfg(test)]
mod tests {
    use bytes::{Bytes, BytesMut};

    use super::*;
    use crate::{DecodeError, EncodeError};

    #[test]
    fn read_u8_normal() {
        let mut buf = Bytes::from_static(&[0x42]);
        assert_eq!(read_u8(&mut buf).unwrap(), 0x42);
        assert_eq!(buf.remaining(), 0);
    }

    #[test]
    fn read_u8_zero() {
        let mut buf = Bytes::from_static(&[0x00]);
        assert_eq!(read_u8(&mut buf).unwrap(), 0x00);
    }

    #[test]
    fn read_u8_max() {
        let mut buf = Bytes::from_static(&[0xFF]);
        assert_eq!(read_u8(&mut buf).unwrap(), 0xFF);
    }

    #[test]
    fn read_u8_empty_buffer() {
        let mut buf = Bytes::new();
        assert_eq!(read_u8(&mut buf), Err(DecodeError::InsufficientBytes { needed: 1 }));
    }

    #[test]
    fn write_u8_roundtrip() {
        let mut wbuf = BytesMut::new();
        write_u8(0xAB, &mut wbuf);
        let mut rbuf = wbuf.freeze();
        assert_eq!(read_u8(&mut rbuf).unwrap(), 0xAB);
    }

    #[test]
    fn read_u16_big_endian() {
        let mut buf = Bytes::from_static(&[0x01, 0x00]);
        assert_eq!(read_u16(&mut buf).unwrap(), 256);
    }

    #[test]
    fn read_u16_zero() {
        let mut buf = Bytes::from_static(&[0x00, 0x00]);
        assert_eq!(read_u16(&mut buf).unwrap(), 0);
    }

    #[test]
    fn read_u16_max() {
        let mut buf = Bytes::from_static(&[0xFF, 0xFF]);
        assert_eq!(read_u16(&mut buf).unwrap(), 65535);
    }

    #[test]
    fn read_u16_one_byte() {
        let mut buf = Bytes::from_static(&[0x01]);
        assert_eq!(read_u16(&mut buf), Err(DecodeError::InsufficientBytes { needed: 2 }));
    }

    #[test]
    fn read_u16_empty() {
        let mut buf = Bytes::new();
        assert_eq!(read_u16(&mut buf), Err(DecodeError::InsufficientBytes { needed: 2 }));
    }

    #[test]
    fn write_u16_roundtrip() {
        let mut wbuf = BytesMut::new();
        write_u16(12345, &mut wbuf);
        let mut rbuf = wbuf.freeze();
        assert_eq!(read_u16(&mut rbuf).unwrap(), 12345);
    }

    #[test]
    fn read_u32_normal() {
        let mut buf = Bytes::from_static(&[0x00, 0x01, 0x00, 0x00]);
        assert_eq!(read_u32(&mut buf).unwrap(), 65536);
    }

    #[test]
    fn read_u32_zero() {
        let mut buf = Bytes::from_static(&[0x00, 0x00, 0x00, 0x00]);
        assert_eq!(read_u32(&mut buf).unwrap(), 0);
    }

    #[test]
    fn read_u32_max() {
        let mut buf = Bytes::from_static(&[0xFF, 0xFF, 0xFF, 0xFF]);
        assert_eq!(read_u32(&mut buf).unwrap(), u32::MAX);
    }

    #[test]
    fn read_u32_three_bytes() {
        let mut buf = Bytes::from_static(&[0x01, 0x02, 0x03]);
        assert_eq!(read_u32(&mut buf), Err(DecodeError::InsufficientBytes { needed: 4 }));
    }

    #[test]
    fn read_u32_empty() {
        let mut buf = Bytes::new();
        assert_eq!(read_u32(&mut buf), Err(DecodeError::InsufficientBytes { needed: 4 }));
    }

    #[test]
    fn write_u32_roundtrip() {
        let mut wbuf = BytesMut::new();
        write_u32(0xDEAD_BEEF, &mut wbuf);
        let mut rbuf = wbuf.freeze();
        assert_eq!(read_u32(&mut rbuf).unwrap(), 0xDEAD_BEEF);
    }

    #[test]
    fn read_string_ascii() {
        let mut wbuf = BytesMut::new();
        write_string("hello", &mut wbuf).unwrap();
        let mut rbuf = wbuf.freeze();
        assert_eq!(read_string(&mut rbuf).unwrap(), "hello");
    }

    #[test]
    fn read_string_empty() {
        let mut buf = Bytes::from_static(&[0x00, 0x00]);
        assert_eq!(read_string(&mut buf).unwrap(), "");
    }

    #[test]
    fn read_string_utf8_multibyte() {
        let mut wbuf = BytesMut::new();
        write_string("你好", &mut wbuf).unwrap();
        let mut rbuf = wbuf.freeze();
        assert_eq!(read_string(&mut rbuf).unwrap(), "你好");
    }

    #[test]
    fn read_string_contains_null() {
        // Manually construct: len=3, "a\0b"
        let mut buf = Bytes::from_static(&[0x00, 0x03, b'a', 0x00, b'b']);
        assert_eq!(
            read_string(&mut buf),
            Err(DecodeError::InvalidUtf8 {
                reason: "contains null character U+0000"
            })
        );
    }

    #[test]
    fn read_string_invalid_utf8() {
        // len=2, invalid utf-8 bytes
        let mut buf = Bytes::from_static(&[0x00, 0x02, 0xFF, 0xFE]);
        assert_eq!(
            read_string(&mut buf),
            Err(DecodeError::InvalidUtf8 {
                reason: "invalid utf-8 sequence"
            })
        );
    }

    #[test]
    fn read_string_incomplete_prefix() {
        let mut buf = Bytes::from_static(&[0x00]);
        assert!(read_string(&mut buf).is_err());
    }

    #[test]
    fn read_string_length_exceeds_data() {
        // len=10 but only 5 bytes of data
        let mut buf = Bytes::from_static(&[0x00, 0x0A, b'h', b'e', b'l', b'l', b'o']);
        assert!(matches!(
            read_string(&mut buf),
            Err(DecodeError::InsufficientBytes { .. })
        ));
    }

    #[test]
    fn write_string_too_long() {
        let long = "a".repeat(65536);
        let mut buf = BytesMut::new();
        assert_eq!(
            write_string(&long, &mut buf),
            Err(EncodeError::StringTooLong { len: 65536 })
        );
    }

    #[test]
    fn write_string_contains_null() {
        let mut buf = BytesMut::new();
        assert_eq!(write_string("ab\0cd", &mut buf), Err(EncodeError::StringContainsNull));
    }

    #[test]
    fn write_string_max_length() {
        let max_str = "a".repeat(65535);
        let mut buf = BytesMut::new();
        assert!(write_string(&max_str, &mut buf).is_ok());
    }

    #[test]
    fn read_binary_normal() {
        let mut buf = Bytes::from_static(&[0x00, 0x03, 0x01, 0x02, 0x03]);
        let data = read_binary(&mut buf).unwrap();
        assert_eq!(&data[..], &[0x01, 0x02, 0x03]);
    }

    #[test]
    fn read_binary_empty() {
        let mut buf = Bytes::from_static(&[0x00, 0x00]);
        let data = read_binary(&mut buf).unwrap();
        assert!(data.is_empty());
    }

    #[test]
    fn write_binary_too_long() {
        let data = vec![0u8; 65536];
        let mut buf = BytesMut::new();
        assert_eq!(
            write_binary(&data, &mut buf),
            Err(EncodeError::StringTooLong { len: 65536 })
        );
    }

    #[test]
    fn read_binary_length_exceeds_data() {
        let mut buf = Bytes::from_static(&[0x00, 0x05, 0x01, 0x02, 0x03]);
        assert!(matches!(
            read_binary(&mut buf),
            Err(DecodeError::InsufficientBytes { .. })
        ));
    }

    #[test]
    fn write_binary_roundtrip() {
        let data = b"mqtt payload";
        let mut wbuf = BytesMut::new();
        write_binary(data, &mut wbuf).unwrap();
        let mut rbuf = wbuf.freeze();
        assert_eq!(&read_binary(&mut rbuf).unwrap()[..], data);
    }

    #[test]
    fn string_pair_roundtrip() {
        let mut wbuf = BytesMut::new();
        write_string_pair("key", "value", &mut wbuf).unwrap();
        let mut rbuf = wbuf.freeze();
        assert_eq!(
            read_string_pair(&mut rbuf).unwrap(),
            ("key".to_owned(), "value".to_owned())
        );
    }

    #[test]
    fn string_pair_empty() {
        let mut wbuf = BytesMut::new();
        write_string_pair("", "", &mut wbuf).unwrap();
        let mut rbuf = wbuf.freeze();
        assert_eq!(read_string_pair(&mut rbuf).unwrap(), (String::new(), String::new()));
    }

    #[test]
    fn string_pair_first_has_null() {
        let mut buf = BytesMut::new();
        assert_eq!(
            write_string_pair("k\0", "v", &mut buf),
            Err(EncodeError::StringContainsNull)
        );
    }

    #[test]
    fn string_pair_second_has_null() {
        let mut buf = BytesMut::new();
        assert_eq!(
            write_string_pair("k", "v\0", &mut buf),
            Err(EncodeError::StringContainsNull)
        );
    }

    #[test]
    fn string_pair_incomplete_second() {
        // Only first string present
        let mut wbuf = BytesMut::new();
        write_string("key", &mut wbuf).unwrap();
        let mut rbuf = wbuf.freeze();
        assert!(read_string_pair(&mut rbuf).is_err());
    }

    #[test]
    fn string_encoded_len_normal() {
        assert_eq!(string_encoded_len(5), 7);
    }

    #[test]
    fn string_encoded_len_zero() {
        assert_eq!(string_encoded_len(0), 2);
    }

    #[test]
    fn binary_encoded_len_normal() {
        assert_eq!(binary_encoded_len(100), 102);
    }

    #[test]
    fn string_pair_encoded_len_normal() {
        assert_eq!(string_pair_encoded_len(3, 5), 12);
    }
}