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
use core::convert::{TryFrom, TryInto};

use heapless::Vec;

use crate::{utils::*, MqttError};

use super::{property, PropertyType};

/// The CONNACK packet is the packet sent by the Server in response to a CONNECT packet received from a Client.
///
/// [MQTT5 Specification](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901074)
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
pub struct ConnAck<'a> {
    /// Position: bit 0 of the Connect Acknowledge Flags.
    ///
    /// The Session Present flag informs the Client whether the Server is
    /// using Session State from a previous connection for this ClientID.
    /// This allows the Client and Server to have a consistent view of the Session State.
    pub session_present: bool,

    /// Byte 2 in the Variable Header is the Connect Reason Code.
    /// [MQTT5 SPECIFICATION](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901079)
    pub code: ConnectReasonCode,

    /// [MQTT5 SPECIFICATION](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901080)
    pub properties: Option<ConnAckProperties<'a>>,
}

impl<'a> ConnAck<'a> {
    pub fn new(code: ConnectReasonCode, session_present: bool) -> Self {
        ConnAck {
            code,
            session_present,
            properties: None,
        }
    }

    pub fn read(buf: &'a [u8], offset: &mut usize) -> Result<Self, MqttError> {
        let flags = buf[*offset];

        // Move offset to return_code
        *offset += 1;

        let return_code = buf[*offset];

        // Move offset to properties_len
        *offset += 1;

        Ok(ConnAck {
            session_present: (flags & 0b1 == 1),
            code: return_code.try_into()?,
            properties: ConnAckProperties::read(buf, offset)?,
        })
    }

    pub fn write(&self, buf: &mut [u8], offset: &mut usize) -> Result<usize, MqttError> {
        // ConnAck (0x20);
        let header: u8 = 0x20;
        let mut flags: u8 = 0b0000_0000;

        if self.session_present {
            flags |= 0b1;
        };

        let return_code = self.code as u8;

        check_remaining(buf, offset, self.len())?;

        write_u8(buf, offset, header);
        let write_len = write_length(buf, offset, self.len())? + 1;
        write_u8(buf, offset, flags);
        write_u8(buf, offset, return_code);

        match &self.properties {
            Some(properties) => properties.write(buf, offset)?,
            None => write_u8(buf, offset, 0),
        }

        Ok(write_len)
    }

    fn len(&self) -> usize {
        // sesssion present + code
        let mut len = 1 + 1;

        match &self.properties {
            Some(properties) => {
                let properties_len = properties.len();
                let properties_len_len = len_len(properties_len);
                len += properties_len_len + properties_len;
            }
            None => {
                // just 1 byte representing 0 len
                len += 1;
            }
        }

        len
    }
}

/// [MQTT5 SPECIFICATION](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901080)
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord, Hash, Default)]
pub struct ConnAckProperties<'a> {
    /// `17 (0x11)` Byte, Identifier of the Session Expiry Interval.
    ///
    /// Followed by the Four Byte Integer representing the Session Expiry Interval in seconds.
    pub session_expiry_interval: Option<u32>,

    /// `18 (0x12)` Byte, Identifier of the Assigned Client Identifier.
    ///
    /// Followed by the UTF-8 string which is the Assigned Client Identifier.
    pub assigned_client_identifier: Option<&'a str>,

    /// `19 (0x13)` Byte, Identifier of the Server Keep Alive.
    ///
    /// Followed by a Two Byte Integer with the Keep Alive time assigned by the Server.
    pub server_keep_alive: Option<u16>,

    /// `21 (0x15)` Byte, Identifier of the Authentication Method.
    ///
    /// Followed by a UTF-8 Encoded String containing the name of the authentication method.
    pub authentication_method: Option<&'a str>,

    /// `22 (0x16)` Byte, Identifier of the Authentication Data.
    ///
    /// Followed by Binary Data containing authentication data.
    pub authentication_data: Option<&'a [u8]>,

    /// `26 (0x1A)` Byte, Identifier of the Response Information.
    ///
    /// Followed by a UTF-8 Encoded String which is used as the basis for creating a Response Topic.
    pub response_information: Option<&'a str>,

    /// `28 (0x1C)` Byte, Identifier of the Server Reference.
    ///
    /// Followed by a UTF-8 Encoded String which can be used by the Client to identify another Server to use.
    pub server_reference: Option<&'a str>,

    /// `31 (0x1F)` Byte Identifier of the Reason String.
    ///
    /// Followed by the UTF-8 Encoded String representing the reason associated with this response.
    pub reason_string: Option<&'a str>,

    /// `33 (0x21)` Byte, Identifier of the Receive Maximum.
    ///
    /// Followed by the Two Byte Integer representing the Receive Maximum value.
    pub receive_max: Option<u16>,

    /// `34 (0x22)` Byte, Identifier of the Topic Alias Maximum.
    ///
    /// Followed by the Two Byte Integer representing the Topic Alias Maximum value.
    pub topic_alias_max: Option<u16>,

    /// `36 (0x24)` Byte, Identifier of the Maximum QoS.
    ///
    /// Followed by a Byte with a value of either 0 or 1.
    pub max_qos: Option<u8>,

    /// `37 (0x25)` Byte, Identifier of Retain Available.
    ///
    /// Followed by a Byte field.
    pub retain_available: Option<u8>,

    /// `38 (0x26)` Byte, Identifier of User Property.
    ///
    /// Followed by a UTF-8 String Pair. This property can be used to provide additional information
    /// to the Client including diagnostic information.
    pub user_properties: Vec<(&'a str, &'a str), 32>,

    /// `39 (0x27)` Byte, Identifier of the Maximum Packet Size.
    ///
    /// Followed by a Four Byte Integer representing the Maximum Packet Size the Server is willing to accept.
    pub max_packet_size: Option<u32>,

    /// `40 (0x28)` Byte, Identifier of Wildcard Subscription Available.
    ///
    /// Followed by a Byte field.
    pub wildcard_subscription_available: Option<u8>,

    /// `41 (0x29)` Byte, Identifier of Subscription Identifier Available.
    ///
    /// Followed by a Byte field.
    pub subscription_identifiers_available: Option<u8>,

    /// `42 (0x2A)` Byte, Identifier of Shared Subscription Available.
    ///
    /// Followed by a Byte field.
    pub shared_subscription_available: Option<u8>,
}

impl<'a> ConnAckProperties<'a> {
    pub fn read(buf: &'a [u8], offset: &mut usize) -> Result<Option<Self>, MqttError> {
        let mut properties = Self::default();

        let properties_len = buf[*offset];

        if properties_len == 0 {
            return Ok(None);
        }

        let mut cursor: usize = 1;

        while cursor < properties_len.into() {
            let mut prop_offset = *offset + cursor;
            let prop = buf[prop_offset];

            prop_offset += 1;
            cursor += 1;
            match property(prop)? {
                PropertyType::AssignedClientIdentifier => {
                    let assigned_client_identifier = read_str(buf, &mut prop_offset)?;
                    cursor += 2 + assigned_client_identifier.len();
                    properties.assigned_client_identifier = Some(assigned_client_identifier);
                }

                PropertyType::AuthenticationData => {
                    let authentication_data = read_bytes(buf, &mut prop_offset)?;
                    cursor += 2 + authentication_data.len();
                    properties.authentication_data = Some(authentication_data);
                }

                PropertyType::AuthenticationMethod => {
                    let authentication_method = read_str(buf, &mut prop_offset)?;
                    cursor += 2 + authentication_method.len();
                    properties.authentication_method = Some(authentication_method);
                }

                PropertyType::MaximumPacketSize => {
                    properties.max_packet_size = Some(read_u32(buf, *offset + cursor));
                    cursor += 4;
                }

                PropertyType::MaximumQos => {
                    properties.max_qos = Some(buf[*offset + cursor]);
                    cursor += 1;
                }

                PropertyType::ReasonString => {
                    let reason_string = read_str(buf, &mut prop_offset)?;
                    cursor += 2 + reason_string.len();
                    properties.reason_string = Some(reason_string);
                }

                PropertyType::ReceiveMaximum => {
                    properties.receive_max = Some(read_u16(buf, *offset + cursor));
                    cursor += 2;
                }

                PropertyType::ResponseInformation => {
                    let response_information = read_str(buf, &mut prop_offset)?;
                    cursor += 2 + response_information.len();
                    properties.response_information = Some(response_information);
                }

                PropertyType::RetainAvailable => {
                    properties.retain_available = Some(buf[*offset + cursor]);
                    cursor += 1;
                }

                PropertyType::ServerKeepAlive => {
                    properties.server_keep_alive = Some(read_u16(buf, *offset + cursor));
                    cursor += 2;
                }

                PropertyType::ServerReference => {
                    let server_reference = read_str(buf, &mut prop_offset)?;
                    cursor += 2 + server_reference.len();
                    properties.server_reference = Some(server_reference);
                }

                PropertyType::SessionExpiryInterval => {
                    properties.session_expiry_interval = Some(read_u32(buf, *offset + cursor));
                    cursor += 4;
                }

                PropertyType::SharedSubscriptionAvailable => {
                    properties.shared_subscription_available = Some(buf[*offset + cursor]);
                    cursor += 1;
                }

                PropertyType::SubscriptionIdentifierAvailable => {
                    properties.subscription_identifiers_available = Some(buf[*offset + cursor]);
                    cursor += 1;
                }

                PropertyType::TopicAliasMaximum => {
                    properties.topic_alias_max = Some(read_u16(buf, *offset + cursor));
                    cursor += 2;
                }

                PropertyType::UserProperty => {
                    let key = read_str(buf, &mut prop_offset)?;
                    let value = read_str(buf, &mut prop_offset)?;
                    cursor += 2 + key.len() + 2 + value.len();
                    properties
                        .user_properties
                        .push((key, value))
                        .map_err(|_| MqttError::TooManyUserProperties)?;
                }

                PropertyType::WildcardSubscriptionAvailable => {
                    properties.wildcard_subscription_available = Some(buf[*offset + cursor]);
                    cursor += 1;
                }
                prop => return Err(MqttError::InvalidPropertyType(prop)),
            }
        }

        *offset += properties.len();
        Ok(Some(properties))
    }

    pub fn write(&self, buf: &mut [u8], offset: &mut usize) -> Result<(), MqttError> {
        write_length(buf, offset, self.len())?;
        if let Some(assigned_client_identifier) = self.assigned_client_identifier {
            write_u8(buf, offset, PropertyType::AssignedClientIdentifier as u8);
            write_bytes_with_len(buf, offset, assigned_client_identifier.as_bytes());
        }

        if let Some(authentication_data) = self.authentication_data {
            write_u8(buf, offset, PropertyType::AuthenticationData as u8);
            write_bytes_with_len(buf, offset, authentication_data);
        }

        if let Some(authentication_method) = self.authentication_method {
            write_u8(buf, offset, PropertyType::AuthenticationMethod as u8);
            write_bytes_with_len(buf, offset, authentication_method.as_bytes());
        }

        if let Some(max_packet_size) = self.max_packet_size {
            write_u8(buf, offset, PropertyType::MaximumPacketSize as u8);
            write_bytes(buf, offset, &max_packet_size.to_be_bytes());
        }

        if let Some(max_qos) = self.max_qos {
            write_u8(buf, offset, PropertyType::MaximumQos as u8);
            write_u8(buf, offset, max_qos);
        }

        if let Some(reason_string) = self.reason_string {
            write_u8(buf, offset, PropertyType::ReasonString as u8);
            write_bytes_with_len(buf, offset, reason_string.as_bytes());
        }

        if let Some(receive_max) = self.receive_max {
            write_u8(buf, offset, PropertyType::ReceiveMaximum as u8);
            write_u16(buf, offset, receive_max);
        }

        if let Some(response_information) = self.response_information {
            write_u8(buf, offset, PropertyType::ResponseInformation as u8);
            write_bytes_with_len(buf, offset, response_information.as_bytes());
        }

        if let Some(retain_available) = self.retain_available {
            write_u8(buf, offset, PropertyType::RetainAvailable as u8);
            write_u8(buf, offset, retain_available);
        }

        if let Some(server_keep_alive) = self.server_keep_alive {
            write_u8(buf, offset, PropertyType::ServerKeepAlive as u8);
            write_u16(buf, offset, server_keep_alive);
        }

        if let Some(server_reference) = self.server_reference {
            write_u8(buf, offset, PropertyType::ServerReference as u8);
            write_bytes_with_len(buf, offset, server_reference.as_bytes());
        }

        if let Some(session_expiry_interval) = self.session_expiry_interval {
            write_u8(buf, offset, PropertyType::SessionExpiryInterval as u8);
            write_bytes(buf, offset, &session_expiry_interval.to_be_bytes());
        }

        if let Some(shared_subscription_available) = self.shared_subscription_available {
            write_u8(buf, offset, PropertyType::SharedSubscriptionAvailable as u8);
            write_u8(buf, offset, shared_subscription_available);
        }

        if let Some(topic_alias_max) = self.topic_alias_max {
            write_u8(buf, offset, PropertyType::TopicAliasMaximum as u8);
            write_u16(buf, offset, topic_alias_max);
        }

        for (key, value) in self.user_properties.iter() {
            write_u8(buf, offset, PropertyType::UserProperty as u8);
            write_bytes_with_len(buf, offset, key.as_bytes());
            write_bytes_with_len(buf, offset, value.as_bytes());
        }

        if let Some(wildcard_subscription_available) = self.wildcard_subscription_available {
            write_u8(
                buf,
                offset,
                PropertyType::WildcardSubscriptionAvailable as u8,
            );
            write_u8(buf, offset, wildcard_subscription_available);
        }

        if let Some(subscription_identifiers_available) = self.subscription_identifiers_available {
            write_u8(
                buf,
                offset,
                PropertyType::SubscriptionIdentifierAvailable as u8,
            );
            write_u8(buf, offset, subscription_identifiers_available);
        }

        Ok(())
    }

    fn len(&self) -> usize {
        let mut len = 0;

        if self.session_expiry_interval.is_some() {
            len += 1 + 4;
        }

        if self.receive_max.is_some() {
            len += 1 + 2;
        }

        if self.max_qos.is_some() {
            len += 1 + 1;
        }

        if self.retain_available.is_some() {
            len += 1 + 1;
        }

        if self.max_packet_size.is_some() {
            len += 1 + 4;
        }

        if self.topic_alias_max.is_some() {
            len += 1 + 2;
        }

        if self.wildcard_subscription_available.is_some() {
            len += 1 + 1;
        }

        if self.subscription_identifiers_available.is_some() {
            len += 1 + 1;
        }

        if self.shared_subscription_available.is_some() {
            len += 1 + 1;
        }

        if self.server_keep_alive.is_some() {
            len += 1 + 2;
        }

        if let Some(reason) = &self.reason_string {
            len += 1 + 2 + reason.len();
        }

        if let Some(id) = &self.assigned_client_identifier {
            len += 1 + 2 + id.len();
        }

        if let Some(info) = &self.response_information {
            len += 1 + 2 + info.len();
        }

        if let Some(reference) = &self.server_reference {
            len += 1 + 2 + reference.len();
        }

        if let Some(authentication_method) = &self.authentication_method {
            len += 1 + 2 + authentication_method.len();
        }

        if let Some(authentication_data) = &self.authentication_data {
            len += 1 + 2 + authentication_data.len();
        }

        for (key, value) in self.user_properties.iter() {
            len += 1 + 2 + key.len() + 2 + value.len();
        }

        len
    }
}

/// Return code in connack
/// [MQTT5 SPECIFICATION](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901079)
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord, Hash, Copy)]
#[repr(u8)]
pub enum ConnectReasonCode {
    /// The Connection is accepted.
    Success = 0,

    /// The Server does not wish to reveal the reason for the failure, or none of the other Reason Codes apply.
    UnspecifiedError = 0x80,

    /// Data within the CONNECT packet could not be correctly parsed.
    MalformedPacket = 0x81,

    /// Data in the CONNECT packet does not conform to this specification.
    ProtocolError = 0x82,

    /// The CONNECT is valid but is not accepted by this Server.
    ImplementationSpecificError = 0x83,

    /// The Server does not support the version of the MQTT protocol requested by the Client.
    UnsupportedProtocolVersion = 0x84,

    /// The Client Identifier is a valid string but is not allowed by the Server.
    ClientIdentifierNotValid = 0x85,

    /// The Server does not accept the User Name or Password specified by the Client.
    BadUserNamePassword = 0x86,

    /// The Client is not authorized to connect.
    NotAuthorized = 0x87,

    /// The MQTT Server is not available.
    ServerUnavailable = 0x88,

    /// The Server is busy. Try again later.
    ServerBusy = 0x89,

    /// This Client has been banned by administrative action. Contact the server administrator.
    Banned = 0x8A,

    /// The authentication method is not supported or does not match the authentication method currently in use.
    BadAuthenticationMethod = 0x8C,

    /// The Will Topic Name is not malformed, but is not accepted by this Server.
    TopicNameInvalid = 0x90,

    /// The CONNECT packet exceeded the maximum permissible size.
    PacketTooLarge = 0x95,

    /// An implementation or administrative imposed limit has been exceeded.
    QuotaExceeded = 0x97,

    /// The Will Payload does not match the specified Payload Format Indicator.
    PayloadFormatInvalid = 0x99,

    /// The Server does not support retained messages, and Will Retain was set to 1.
    RetainNotSupported = 0x9A,

    /// The Server does not support the QoS set in Will QoS.
    QoSNotSupported = 0x9B,

    /// The Client should temporarily use another server.
    UseAnotherServer = 0x9C,

    /// The Client should permanently use another server.
    ServerMoved = 0x9D,

    /// The connection rate limit has been exceeded.
    ConnectionRateExceeded = 0x9F,
}

impl TryFrom<u8> for ConnectReasonCode {
    type Error = MqttError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        let code = match value {
            0 => ConnectReasonCode::Success,
            128 => ConnectReasonCode::UnspecifiedError,
            129 => ConnectReasonCode::MalformedPacket,
            130 => ConnectReasonCode::ProtocolError,
            131 => ConnectReasonCode::ImplementationSpecificError,
            132 => ConnectReasonCode::UnsupportedProtocolVersion,
            133 => ConnectReasonCode::ClientIdentifierNotValid,
            134 => ConnectReasonCode::BadUserNamePassword,
            135 => ConnectReasonCode::NotAuthorized,
            136 => ConnectReasonCode::ServerUnavailable,
            137 => ConnectReasonCode::ServerBusy,
            138 => ConnectReasonCode::Banned,
            140 => ConnectReasonCode::BadAuthenticationMethod,
            144 => ConnectReasonCode::TopicNameInvalid,
            149 => ConnectReasonCode::PacketTooLarge,
            151 => ConnectReasonCode::QuotaExceeded,
            153 => ConnectReasonCode::PayloadFormatInvalid,
            154 => ConnectReasonCode::RetainNotSupported,
            155 => ConnectReasonCode::QoSNotSupported,
            156 => ConnectReasonCode::UseAnotherServer,
            157 => ConnectReasonCode::ServerMoved,
            159 => ConnectReasonCode::ConnectionRateExceeded,
            code => return Err(MqttError::InvalidConnectReasonCode(code)),
        };

        Ok(code)
    }
}

#[cfg(test)]
mod test {
    use super::{ConnAck, ConnAckProperties, ConnectReasonCode};

    fn sample<'a>() -> ConnAck<'a> {
        let properties = ConnAckProperties {
            session_expiry_interval: Some(1234),
            receive_max: Some(432),
            max_qos: Some(2),
            retain_available: Some(1),
            max_packet_size: Some(100),
            assigned_client_identifier: Some("test"),
            topic_alias_max: Some(456),
            reason_string: Some("test"),
            user_properties: heapless::Vec::<_, 32>::from_slice(&[("test", "test")]).unwrap(),
            wildcard_subscription_available: Some(1),
            subscription_identifiers_available: Some(1),
            shared_subscription_available: Some(0),
            server_keep_alive: Some(1234),
            response_information: Some("test"),
            server_reference: Some("test"),
            authentication_method: Some("test"),
            authentication_data: Some(&[1, 2, 3, 4]),
        };

        ConnAck {
            session_present: false,
            code: ConnectReasonCode::Success,
            properties: Some(properties),
        }
    }

    fn sample_bytes() -> Vec<u8> {
        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
        ]
    }

    #[test]
    fn connack_len() {
        let expected = 87;
        let actual = sample().len();
        assert_eq!(expected, actual);
    }
    #[test]
    fn connack_encode() {
        let expected = sample_bytes();
        let mut buf = [0u8; 89];
        sample().write(&mut buf, &mut 0).unwrap();

        assert_eq!(expected.as_slice(), buf);
    }

    #[test]
    fn connack_decode() {
        let bytes = &sample_bytes()[2..];
        let expected = sample();
        let actual = ConnAck::read(bytes, &mut 0).unwrap();
        assert_eq!(expected, actual);
    }

    #[test]
    fn connack_props_encode() {
        let expected = &sample_bytes()[4..];
        let mut buf = [0u8; 85];
        sample()
            .properties
            .unwrap()
            .write(&mut buf, &mut 0)
            .unwrap();
        assert_eq!(expected.len(), buf.len());

        assert_eq!(expected, buf);
    }

    #[test]
    fn connack_props_decode() {
        let bytes = &sample_bytes()[4..];
        let expected = sample().properties.unwrap();
        let actual = ConnAckProperties::read(bytes, &mut 0).unwrap().unwrap();
        assert_eq!(expected, actual);
    }
}