gmqtt 0.1.1

A no_std, no_alloc MQTTv5 packet parsing library for embedded devices
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
mod disconnect;
mod ping;
mod pubcomp;
mod pubrec;
mod pubrel;
mod unsuback;
mod unsubscribe;

pub(crate) mod subscribe;

pub mod connack;
pub mod connect;
pub mod puback;
pub mod publish;
pub mod suback;

use core::convert::TryFrom;
use num_enum::TryFromPrimitive;

use crate::{MqttError, Pid, QoS};

pub use self::{
    connack::ConnAck,
    connect::Connect,
    disconnect::Disconnect,
    ping::{PingReq, PingResp},
    puback::PubAck,
    pubcomp::PubComp,
    publish::Publish,
    pubrec::PubRec,
    pubrel::PubRel,
    suback::SubAck,
    subscribe::Subscribe,
    unsuback::UnsubAck,
    unsubscribe::Unsubscribe,
};

#[repr(u8)]
#[derive(TryFromPrimitive, Debug, Clone, Copy, PartialEq, Eq)]
pub enum PropertyType {
    PayloadFormatIndicator = 0x01,
    MessageExpiryInterval = 0x02,
    ContentType = 0x03,
    ResponseTopic = 0x08,
    CorrelationData = 0x09,
    SubscriptionIdentifier = 0x0B,
    SessionExpiryInterval = 0x11,
    AssignedClientIdentifier = 0x12,
    ServerKeepAlive = 0x13,
    AuthenticationMethod = 0x15,
    AuthenticationData = 0x16,
    RequestProblemInformation = 0x17,
    WillDelayInterval = 0x18,
    RequestResponseInformation = 0x19,
    ResponseInformation = 0x1A,
    ServerReference = 0x1C,
    ReasonString = 0x1F,
    ReceiveMaximum = 0x21,
    TopicAliasMaximum = 0x22,
    TopicAlias = 0x23,
    MaximumQos = 0x24,
    RetainAvailable = 0x25,
    UserProperty = 0x26,
    MaximumPacketSize = 0x27,
    WildcardSubscriptionAvailable = 0x28,
    SubscriptionIdentifierAvailable = 0x29,
    SharedSubscriptionAvailable = 0x2A,
}

/// Packet type variant, without the associated data.
#[repr(u8)]
#[derive(TryFromPrimitive, Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum PacketType {
    Connect = 0x01,
    ConnAck = 0x02,
    Publish = 0x03,
    PubAck = 0x04,
    PubRec = 0x05,
    PubRel = 0x06,
    PubComp = 0x07,
    Subscribe = 0x08,
    SubAck = 0x09,
    Unsubscribe = 0x0A,
    UnsubAck = 0x0B,
    PingReq = 0x0C,
    PingResp = 0x0D,
    Disconnect = 0x0E,
}

fn property(code: u8) -> Result<PropertyType, MqttError> {
    PropertyType::try_from(code).map_err(|_| MqttError::InvalidPropertyByte(code))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Header {
    pub typ: PacketType,
    pub dup: bool,
    pub qos: QoS,
    pub retain: bool,
}

impl Header {
    pub fn new(hd: u8) -> Result<Header, MqttError> {
        let typ: PacketType =
            PacketType::try_from(hd >> 4).map_err(|_| MqttError::InvalidHeader)?;

        let flags_ok = match typ {
            PacketType::Connect => hd & 0b1111 == 0,
            PacketType::ConnAck => hd & 0b1111 == 0,
            PacketType::Publish => true,
            PacketType::PubAck => hd & 0b1111 == 0,
            PacketType::PubRec => hd & 0b1111 == 0,
            PacketType::PubRel => hd & 0b1111 == 0b0010,
            PacketType::PubComp => hd & 0b1111 == 0,
            PacketType::Subscribe => hd & 0b1111 == 0b0010,
            PacketType::SubAck => hd & 0b1111 == 0,
            PacketType::Unsubscribe => hd & 0b1111 == 0b0010,
            PacketType::UnsubAck => hd & 0b1111 == 0,
            PacketType::PingReq => hd & 0b1111 == 0,
            PacketType::PingResp => hd & 0b1111 == 0,
            PacketType::Disconnect => hd & 0b1111 == 0,
        };

        if !flags_ok {
            return Err(MqttError::InvalidHeader);
        }

        Ok(Header {
            typ,
            dup: hd & 0b1000 != 0,
            qos: QoS::try_from((hd & 0b110) >> 1)?,
            retain: hd & 1 == 1,
        })
    }
}

/// Encapsulates all MQTT packet types
#[derive(Debug, Clone, PartialEq)]
pub enum Packet<'a> {
    Connect(Connect<'a>),
    ConnAck(ConnAck<'a>),
    Publish(Publish<'a>),
    PubAck(PubAck<'a>),
    PubRec(PubRec<'a>),
    PubRel(PubRel<'a>),
    PubComp(PubComp<'a>),
    Subscribe(Subscribe<'a>),
    SubAck(SubAck<'a>),
    Unsubscribe(Unsubscribe<'a>),
    UnsubAck(UnsubAck<'a>),
    PingReq,
    PingResp,
    Disconnect(Disconnect<'a>),
}

impl<'a> Packet<'a> {
    pub fn type_name(&self) -> &'static str {
        match *self {
            Packet::Connect(_) => "Connect",
            Packet::ConnAck(_) => "ConnAck",
            Packet::Publish(_) => "Publish",
            Packet::PubAck(_) => "PubAck",
            Packet::PubRec(_) => "PubRec",
            Packet::PubRel(_) => "PubRel",
            Packet::PubComp(_) => "PubComp",
            Packet::Subscribe(_) => "Subscribe",
            Packet::SubAck(_) => "SubAck",
            Packet::Unsubscribe(_) => "Unsubscribe",
            Packet::UnsubAck(_) => "UnsubAck",
            Packet::PingReq => "PingReq",
            Packet::PingResp => "PingResp",
            Packet::Disconnect(_) => "Disconnect",
        }
    }
}

pub fn clone_packet(input: &[u8], output: &mut [u8]) -> Result<usize, MqttError> {
    if input.is_empty() {
        return Ok(0);
    }

    let mut offset = 0;

    while Header::new(input[offset]).is_err() {
        offset += 1;
        if input[offset..].is_empty() {
            return Ok(0);
        }
    }

    let start = offset;

    if let Some((_, remaining_len)) = read_header(input, &mut offset)? {
        let end = offset + remaining_len;
        let len = end - start;
        output[..len].copy_from_slice(&input[start..end]);
        return Ok(end);
    }

    Ok(0)
}

/// TODO: Return None if not enough bytes, MqttError::WaitForMoreBytes
pub fn read_packet(buf: &[u8]) -> Result<Packet, MqttError> {
    let mut offset = 0;
    let packet_header = read_header(buf, &mut offset)?;

    match packet_header {
        Some(packet_header) => {
            let (header, length) = packet_header;
            if length == 0 {
                // no payload packets
                return match header.typ {
                    PacketType::PingReq => Ok(Packet::PingReq),
                    PacketType::PingResp => Ok(Packet::PingResp),
                    PacketType::Disconnect => Ok(Packet::Disconnect(Disconnect::default())),
                    _ => Err(MqttError::PayloadRequired),
                };
            }

            // TODO: clone_packet_from_bytes test

            let packet = match header.typ {
                PacketType::Connect => Packet::Connect(Connect::read(buf, &mut offset)?),
                PacketType::ConnAck => Packet::ConnAck(ConnAck::read(buf, &mut offset)?),
                PacketType::Publish => Packet::Publish(Publish::read(header, buf, &mut offset)?),
                PacketType::PubAck => {
                    let inner = if length == 2 {
                        let pid = Pid::read(buf, &mut offset)?;

                        PubAck::new(pid)
                    } else {
                        PubAck::read(buf, &mut offset)?
                    };

                    Packet::PubAck(inner)
                }
                PacketType::PubRec => Packet::PubRec(PubRec::read(buf, &mut offset)?),
                PacketType::PubRel => Packet::PubRel(PubRel::read(buf, &mut offset)?),
                PacketType::PubComp => Packet::PubComp(PubComp::read(buf, &mut offset)?),
                PacketType::Subscribe => Packet::Subscribe(Subscribe::read(buf, &mut offset)?),
                PacketType::SubAck => Packet::SubAck(SubAck::read(buf, &mut offset)?),
                PacketType::Unsubscribe => {
                    Packet::Unsubscribe(Unsubscribe::read(buf, &mut offset)?)
                }
                PacketType::UnsubAck => Packet::UnsubAck(UnsubAck::read(buf, &mut offset)?),
                PacketType::PingReq => Packet::PingReq,
                PacketType::PingResp => Packet::PingResp,
                PacketType::Disconnect => Packet::Disconnect(Disconnect::read(buf, &mut offset)?),
            };

            Ok(packet)
        }
        None => Err(MqttError::InvalidHeader),
    }
}

pub fn write_packet(packet: &Packet, buf: &mut [u8]) -> Result<usize, MqttError> {
    let mut offset = 0;

    let write_len = match packet {
        Packet::Connect(connect) => connect.write(buf, &mut offset)?,
        Packet::ConnAck(connack) => connack.write(buf, &mut offset)?,
        Packet::Publish(publish) => publish.write(buf, &mut offset)?,
        Packet::PubAck(puback) => puback.write(buf, &mut offset)?,
        Packet::PubRec(pubrec) => pubrec.write(buf, &mut offset)?,
        Packet::PubRel(pubrel) => pubrel.write(buf, &mut offset)?,
        Packet::PubComp(pubcomp) => pubcomp.write(buf, &mut offset)?,
        Packet::Subscribe(subscribe) => subscribe.write(buf, &mut offset)?,
        Packet::SubAck(suback) => suback.write(buf, &mut offset)?,
        Packet::Unsubscribe(unsubscribe) => unsubscribe.write(buf, &mut offset)?,
        Packet::UnsubAck(unsuback) => unsuback.write(buf, &mut offset)?,
        Packet::PingReq => PingReq::write(buf, &mut offset)?,
        Packet::PingResp => PingResp::write(buf, &mut offset)?,
        Packet::Disconnect(disconnect) => disconnect.write(buf, &mut offset)?,
    };

    Ok(write_len)
}

/// Read the parsed header and remaining_len from the buffer. Only return Some() and advance the
/// buffer position if there is enough data in the buffer to read the full packet.
pub fn read_header(buf: &[u8], offset: &mut usize) -> Result<Option<(Header, usize)>, MqttError> {
    let mut len: usize = 0;
    for pos in 0..=3 {
        if buf.len() > *offset + pos + 1 {
            let byte = buf[*offset + pos + 1];
            len += (byte as usize & 0x7F) << (pos * 7);

            if (byte & 0x80) == 0 {
                // Continuation bit == 0, length is parsed
                if buf.len() < *offset + 2 + pos + len {
                    // Won't be able to read full packet
                    return Ok(None);
                }

                // Parse header byte, skip past the header, and return
                let header = Header::new(buf[*offset])?;

                *offset += pos + 2;
                return Ok(Some((header, len)));
            }
        } else {
            // Couldn't read full length
            return Ok(None);
        }
    }
    // Continuation byte == 1 four times, that's illegal.
    Err(MqttError::InvalidHeader)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn read_connect_packet() {
        let packet = vec![
            0x10, // packet type
            0x9d, // remaining len
            0x01, // remaining len
            0x00, 0x04, // 4
            0x4d, // M
            0x51, // Q
            0x54, // T
            0x54, // T
            0x05, // Level
            0xc6, // connect flags
            0x00, 0x00, // keep alive
            0x2f, // properties len
            0x11, 0x00, 0x00, 0x04, 0xd2, // session expiry interval
            0x21, 0x01, 0xb0, // receive_maximum
            0x27, 0x00, 0x00, 0x00, 0x64, // max packet size
            0x22, 0x01, 0xc8, // topic_alias_max
            0x19, 0x01, // request_response_info
            0x17, 0x01, // request_problem_info
            0x15, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // authentication_method
            0x16, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04, // authentication_data
            0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04, 0x74, 0x65, 0x73,
            0x74, // user
            0x00, 0x09, 0x6d, 0x79, 0x2d, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, // client id
            0x2f, // will properties len
            0x01, 0x00, // payload format indicator
            0x02, 0x00, 0x00, 0x10, 0xe1, // message expiry interval
            0x03, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // content type
            0x08, 0x00, 0x05, 0x74, 0x6f, 0x70, 0x69, 0x63, // response topic
            0x09, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04, // correlation_data
            0x18, 0x00, 0x00, 0x04, 0xd2, // will delay interval
            0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04, 0x74, 0x65, 0x73,
            0x74, // will user properties
            0x00, 0x0f, 0x6d, 0x79, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x2f, 0x73, 0x74, 0x61,
            0x74, 0x75, 0x73, // will topic
            0x00, 0x04, 0x64, 0x65, 0x61, 0x64, // will payload
            0x00, 0x06, 0x6d, 0x61, 0x74, 0x74, 0x65, 0x6f, // username
            0x00, 0x07, 0x63, 0x6f, 0x6c, 0x6c, 0x69, 0x6e, 0x61, // password
        ];

        let mut offset = 0;
        let header = read_header(&packet, &mut offset).unwrap().unwrap();
        assert_eq!(PacketType::Connect, header.0.typ);

        assert_eq!(offset, 3);
    }

    #[test]
    fn read_connack_packet() {
        let packet = vec![
            0x20, // Packet type
            0x57, // Remaining length
            0x00, 0x00, // Session, code
            0x54, // Properties length
            0x12, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // Assigned client identifier
            0x16, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04, // authentication data
            0x15, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // authentication method
            0x27, 0x00, 0x00, 0x00, 0x64, // Maximum packet size
            0x24, 0x02, // Maximum qos
            0x1f, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // Reason string
            0x21, 0x01, 0xb0, // Receive maximum
            0x1a, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // response_information
            0x25, 0x01, // Retain available
            0x13, 0x04, 0xd2, // server keep_alive
            0x1c, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // server reference
            0x11, 0x00, 0x00, 0x04, 0xd2, // Session expiry interval
            0x2a, 0x00, // shared_subscription_available
            0x22, 0x01, 0xc8, // Topic alias max
            0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04, 0x74, 0x65, 0x73,
            0x74, // user properties
            0x28, 0x01, // wildcard_subscription_available
            0x29, 0x01, // subscription_identifiers_available
        ];

        let mut offset = 0;
        let header = read_header(&packet, &mut offset).unwrap().unwrap();
        assert_eq!(PacketType::ConnAck, header.0.typ);

        assert_eq!(offset, 2);
    }

    #[test]
    fn read_disconnect_packet() {
        let packet = vec![
            0xE0, // Packet type
            0x00, // Remaining length
        ];

        let mut offset = 0;
        let header = read_header(&packet, &mut offset).unwrap().unwrap();
        assert_eq!(PacketType::Disconnect, header.0.typ);

        assert_eq!(offset, 2);
    }

    #[test]
    fn read_pingreq_packet() {
        let packet = vec![
            0xC0, // Packet type
            0x00, // Remaining length
        ];

        let mut offset = 0;
        let header = read_header(&packet, &mut offset).unwrap().unwrap();
        assert_eq!(PacketType::PingReq, header.0.typ);

        assert_eq!(offset, 2);
    }

    #[test]
    fn read_pingresp_packet() {
        let packet = vec![
            0xD0, // Packet type
            0x00, // Remaining length
        ];

        let mut offset = 0;
        let header = read_header(&packet, &mut offset).unwrap().unwrap();
        assert_eq!(PacketType::PingResp, header.0.typ);

        assert_eq!(offset, 2);
    }

    #[test]
    fn read_puback_packet() {
        let packet = vec![
            0x40, // payload type
            0x18, // remaining length
            0x00, 0x2a, // packet id
            0x10, // reason
            0x14, // properties len
            0x1f, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // reason_string
            0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04, 0x74, 0x65, 0x73,
            0x74, // user properties
        ];

        let mut offset = 0;
        let header = read_header(&packet, &mut offset).unwrap().unwrap();
        assert_eq!(PacketType::PubAck, header.0.typ);

        assert_eq!(offset, 2);
    }
    #[test]
    fn read_pubcomp_packet() {
        let packet = vec![
            0x70, // payload type
            0x18, // remaining length
            0x00, 0x2a, // packet id
            0x92, // reason
            0x14, // properties len
            0x1f, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // reason_string
            0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04, 0x74, 0x65, 0x73,
            0x74, // user properties
        ];

        let mut offset = 0;
        let header = read_header(&packet, &mut offset).unwrap().unwrap();
        assert_eq!(PacketType::PubComp, header.0.typ);

        assert_eq!(offset, 2);
    }

    #[test]
    fn read_publish_packet() {
        let packet = vec![
            0x34, // payload type
            0x40, // remaining len
            0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // topic name
            0x00, 0x2a, // pkid
            0x33, // properties len
            0x01, 0x01, // payload format indicator
            0x02, 0x00, 0x00, 0x10, 0xe1, // message_expiry_interval
            0x23, 0x00, 0x64, // topic alias
            0x08, 0x00, 0x05, 0x74, 0x6f, 0x70, 0x69, 0x63, // response topic
            0x09, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04, // correlation_data
            0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04, 0x74, 0x65, 0x73,
            0x74, // user properties
            0x0b, 0x78, // subscription_identifier
            0x0b, 0x80, 0x80, 0x01, // subscription_identifier
            0x03, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // content_type
            0x74, 0x65, 0x73, 0x74, // payload
        ];

        let mut offset = 0;
        let header = read_header(&packet, &mut offset).unwrap().unwrap();
        assert_eq!(PacketType::Publish, header.0.typ);

        assert_eq!(offset, 2);
    }

    #[test]
    fn read_pubrec_packet() {
        let packet = vec![
            0x50, // payload type
            0x18, // remaining length
            0x00, 0x2a, // packet id
            0x10, // reason
            0x14, // properties len
            0x1f, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // reason_string
            0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04, 0x74, 0x65, 0x73,
            0x74, // user properties
        ];

        let mut offset = 0;
        let header = read_header(&packet, &mut offset).unwrap().unwrap();
        assert_eq!(PacketType::PubRec, header.0.typ);

        assert_eq!(offset, 2);
    }
    #[test]
    fn read_pubrel_packet() {
        let packet = vec![
            0x62, // payload type
            0x18, // remaining length
            0x00, 0x2a, // packet id
            0x92, // reason
            0x14, // properties len
            0x1f, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // reason_string
            0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04, 0x74, 0x65, 0x73,
            0x74, // user properties
        ];

        let mut offset = 0;
        let header = read_header(&packet, &mut offset).unwrap().unwrap();
        assert_eq!(PacketType::PubRel, header.0.typ);

        assert_eq!(offset, 2);
    }
    #[test]
    fn read_suback_packet() {
        let packet = vec![
            0x90, // packet type
            0x1b, // remaining len
            0x00, 0x2a, // pkid
            0x14, // properties len
            0x1f, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74,
            0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // user properties
            0x00, 0x01, 0x02, 0x80, // return codes
        ];

        let mut offset = 0;
        let header = read_header(&packet, &mut offset).unwrap().unwrap();
        assert_eq!(PacketType::SubAck, header.0.typ);

        assert_eq!(offset, 2);
    }
    #[test]
    fn read_subscribe_packet() {
        let packet = vec![
            0x82, // packet type
            0x1a, // remaining length
            0x00, 0x2a, // pkid
            0x0f, // properties len
            0x0b, 0x64, // subscription identifier
            0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04, 0x74, 0x65, 0x73,
            0x74, // user properties
            0x00, 0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, // filter
            0x2d, // options
        ];

        let mut offset = 0;
        let header = read_header(&packet, &mut offset).unwrap().unwrap();
        assert_eq!(PacketType::Subscribe, header.0.typ);

        assert_eq!(offset, 2);
    }
    #[test]
    fn read_unubscribe_packet() {
        let packet = vec![
            0xa2, // packet type
            0x1e, // remaining len
            0x00, 0x0a, // pkid
            0x0d, // properties len
            0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04, 0x74, 0x65, 0x73,
            0x74, // user properties
            0x00, 0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f, // filter 1
            0x00, 0x05, 0x77, 0x6f, 0x72, 0x6c, 0x64, // filter 2
        ];

        let mut offset = 0;
        let header = read_header(&packet, &mut offset).unwrap().unwrap();
        assert_eq!(PacketType::Unsubscribe, header.0.typ);

        assert_eq!(offset, 2);
    }
    #[test]
    fn read_unsuback_packet() {
        let packet = vec![
            0xb0, // packet type
            0x19, // remaining len
            0x00, 0x0a, // pkid
            0x14, // properties len
            0x1f, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // reason string
            0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04, 0x74, 0x65, 0x73,
            0x74, // user properties
            0x87, 0x8f, // reasons
        ];

        let mut offset = 0;
        let header = read_header(&packet, &mut offset).unwrap().unwrap();
        assert_eq!(PacketType::UnsubAck, header.0.typ);

        assert_eq!(offset, 2);
    }

    #[test]
    fn clone_packet_from_bytes_exact() {
        let bytes = vec![
            0x77, 0x11, 0x22, 0xbe, 0xef, // some random data
            0x90, // packet type
            0x1b, // remaining len
            0x00, 0x2a, // pkid
            0x14, // properties len
            0x1f, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74,
            0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // user properties
            0x00, 0x01, 0x02, 0x80, // return codes
            0x77, 0x1f, 0xde, 0xad, // more random data
        ];

        let mut packet_bytes = [0x00u8; 64];

        let len = clone_packet(&bytes, &mut packet_bytes).unwrap();

        let packet = read_packet(&packet_bytes[..len]).unwrap();

        assert!(matches!(packet, Packet::SubAck(_)));
    }

    #[ignore = "read_packet should decode MQTT packet from slice which length is bigger than exact packet length"]
    #[test]
    fn clone_packet_from_bytes() {
        let bytes = vec![
            0x77, 0x11, 0x22, 0xbe, 0xef, // some random data
            0x90, // packet type
            0x1b, // remaining len
            0x00, 0x2a, // pkid
            0x14, // properties len
            0x1f, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74,
            0x00, 0x04, 0x74, 0x65, 0x73, 0x74, // user properties
            0x00, 0x01, 0x02, 0x80, // return codes
            0x77, 0x1f, 0xde, 0xad, // more random data
        ];

        let mut packet_bytes = [0x00u8; 64];

        let _len = clone_packet(&bytes, &mut packet_bytes).unwrap();

        let packet = read_packet(&packet_bytes).unwrap();

        assert!(matches!(packet, Packet::SubAck(_)));
    }

    #[test]
    fn write_suback_packet() {
        let expected = vec![
            0x90, // packet type
            0x07, // remaining len
            0x00, 0x2a, // pkid
            0x00, // properties len
            0x00, 0x01, 0x02, 0x80, // return codes
        ];

        use suback::SubscribeReasonCode;

        let mut reason_codes: heapless::Vec<_, 32> = heapless::Vec::new();
        reason_codes.push(SubscribeReasonCode::QoS0).unwrap();
        reason_codes.push(SubscribeReasonCode::QoS1).unwrap();
        reason_codes.push(SubscribeReasonCode::QoS2).unwrap();
        reason_codes.push(SubscribeReasonCode::Unspecified).unwrap();

        let packet = Packet::SubAck(SubAck {
            pid: crate::Pid::new(42),
            reason_codes,
            properties: None,
        });

        let mut packet_bytes = [0x00u8; 64];

        let len = write_packet(&packet, &mut packet_bytes).unwrap();

        assert_eq!(expected, packet_bytes[..len]);
    }
}