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
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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
//! CONNECT and CONNACK packet encoding/decoding [MQTT-3.1, MQTT-3.2]
//!
//! ```text
//! CONNECT packet format [MQTT-3.1]:
//!
//!   Fixed Header:
//!     Byte 1: 0x10 (type=1, flags=0b0000)
//!     Byte 2..N: Remaining Length (variable-length integer)
//!
//!   Variable Header:
//!     Protocol Name:    2-byte length + "MQTT" (6 bytes total)
//!     Protocol Level:   1 byte (0x04 for v3.1.1)
//!     Connect Flags:    1 byte
//!       Bit 7: Username Flag
//!       Bit 6: Password Flag
//!       Bit 5: Will Retain
//!       Bit 4-3: Will QoS
//!       Bit 2: Will Flag
//!       Bit 1: Clean Session
//!       Bit 0: Reserved (must be 0)
//!     Keep Alive:       2 bytes (big-endian seconds)
//!
//!   Payload (in order, presence determined by flags):
//!     Client Identifier:  UTF-8 string (always present)
//!     Will Topic:         UTF-8 string (if Will Flag = 1)
//!     Will Message:       binary data  (if Will Flag = 1)
//!     Username:           UTF-8 string (if Username Flag = 1)
//!     Password:           binary data  (if Password Flag = 1)
//!
//! CONNACK packet format [MQTT-3.2]:
//!
//!   Fixed Header:
//!     Byte 1: 0x20 (type=2, flags=0b0000)
//!     Byte 2: 0x02 (remaining length, always 2)
//!
//!   Variable Header:
//!     Connect Acknowledge Flags: 1 byte (bit 0 = Session Present)
//!     Connect Return Code:       1 byte (0x00–0x05)
//!
//! DISCONNECT packet format [MQTT-3.14]:
//!
//!   Fixed Header:
//!     Byte 1: 0xE0 (type=14, flags=0b0000)
//!     Byte 2: 0x00 (remaining length, always 0)
//!
//!   No variable header, no payload.
//! ```

use bytes::{Bytes, BytesMut};

use crate::{DecodeError, EncodeError, PacketType, QoS, primitives};

/// Protocol name, fixed to "MQTT" in v3.1.1 [MQTT-3.1.2-1]
const PROTOCOL_NAME: &str = "MQTT";

/// Protocol level, fixed to 4 in v3.1.1 [MQTT-3.1.2-2]
const PROTOCOL_LEVEL: u8 = 4;

/// Last Will and Testament message [MQTT-3.1.2.5 – MQTT-3.1.3.3]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Will {
    /// Topic to publish the will message to
    pub topic: String,
    /// Will message payload (arbitrary bytes)
    pub message: Bytes,
    /// QoS level for the will message delivery
    pub qos: QoS,
    /// Whether the will message should be retained by the broker
    pub retain: bool,
}

/// CONNECT packet — client requests a connection to the broker [MQTT-3.1]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Connect {
    /// If true, the broker discards any existing session state [MQTT-3.1.2.4]
    pub clean_session: bool,
    /// Maximum idle interval in seconds before the broker closes the connection
    pub keep_alive: u16,
    /// Client identifier (may be empty for auto-assigned IDs)
    pub client_id: String,
    /// Optional last will and testament
    pub will: Option<Will>,
    /// Optional username for authentication
    pub username: Option<String>,
    /// Optional password for authentication (requires username)
    pub password: Option<Bytes>,
}

impl Connect {
    /// Fixed header flags are always 0b0000 [MQTT-2.2.2, Table 2.2]
    const FLAGS: u8 = 0b0000;

    /// Variable header fixed part: protocol name + level(1) + flags(1) + keep_alive(2)
    const VARIABLE_HEADER_LEN: usize = primitives::string_encoded_len(PROTOCOL_NAME.len()) + 1 + 1 + 2;

    pub(super) fn flags(&self) -> u8 {
        Self::FLAGS
    }

    pub(super) fn encoded_body_len(&self) -> usize {
        let mut len = Self::VARIABLE_HEADER_LEN;
        // Payload
        len += primitives::string_encoded_len(self.client_id.len());
        if let Some(will) = &self.will {
            len += primitives::string_encoded_len(will.topic.len());
            len += primitives::binary_encoded_len(will.message.len());
        }
        if let Some(username) = &self.username {
            len += primitives::string_encoded_len(username.len());
        }
        if let Some(password) = &self.password {
            len += primitives::binary_encoded_len(password.len());
        }
        len
    }

    pub(super) fn encode_body(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
        self.validate()?;

        primitives::write_string(PROTOCOL_NAME, buf)?;
        primitives::write_u8(PROTOCOL_LEVEL, buf);
        primitives::write_u8(self.connect_flags(), buf);
        primitives::write_u16(self.keep_alive, buf);

        // Payload fields follow a fixed order, each present only if its flag says so
        primitives::write_string(&self.client_id, buf)?;
        if let Some(will) = &self.will {
            primitives::write_string(&will.topic, buf)?;
            primitives::write_binary(&will.message, buf)?;
        }
        if let Some(username) = &self.username {
            primitives::write_string(username, buf)?;
        }
        if let Some(password) = &self.password {
            primitives::write_binary(password, buf)?;
        }

        Ok(())
    }

    pub(super) fn decode_body(header_flags: u8, mut buf: Bytes) -> Result<Self, DecodeError> {
        if header_flags != Self::FLAGS {
            return Err(DecodeError::InvalidFlags {
                packet_type: PacketType::Connect,
                flags: header_flags,
            });
        }

        let protocol_name = primitives::read_string(&mut buf)?;
        if protocol_name != PROTOCOL_NAME {
            return Err(DecodeError::ProtocolError {
                reason: "protocol name must be \"MQTT\"",
            });
        }

        let level = primitives::read_u8(&mut buf)?;
        if level != PROTOCOL_LEVEL {
            return Err(DecodeError::ProtocolError {
                reason: "protocol level must be 4 for MQTT 3.1.1",
            });
        }

        let flags = primitives::read_u8(&mut buf)?;
        // Bit 0 is reserved; a set bit means the sender is not speaking v3.1.1 [MQTT-3.1.2-3]
        if flags & 0x01 != 0 {
            return Err(DecodeError::ProtocolError {
                reason: "connect flags reserved bit must be 0",
            });
        }

        // Connect flags byte layout [MQTT-3.1.2.3]:
        //   bit 7 username | bit 6 password | bit 5 will retain
        //   bits 4-3 will QoS | bit 2 will | bit 1 clean session | bit 0 reserved
        let clean_session = (flags >> 1) & 0x01 == 1;
        let will_flag = (flags >> 2) & 0x01 == 1;
        let will_qos_raw = (flags >> 3) & 0x03;
        let will_retain = (flags >> 5) & 0x01 == 1;
        let password_flag = (flags >> 6) & 0x01 == 1;
        let username_flag = (flags >> 7) & 0x01 == 1;

        // With no will, its QoS and retain bits carry no meaning and must be zero [MQTT-3.1.2-13]
        if !will_flag {
            if will_qos_raw != 0 {
                return Err(DecodeError::ProtocolError {
                    reason: "will_qos must be 0 when will_flag is 0",
                });
            }
            if will_retain {
                return Err(DecodeError::ProtocolError {
                    reason: "will_retain must be 0 when will_flag is 0",
                });
            }
        }

        let will_qos = QoS::try_from(will_qos_raw)?;

        if !username_flag && password_flag {
            return Err(DecodeError::ProtocolError {
                reason: "password_flag=1 requires username_flag=1",
            });
        }

        let keep_alive = primitives::read_u16(&mut buf)?;
        let client_id = primitives::read_string(&mut buf)?;

        let will = if will_flag {
            let topic = primitives::read_string(&mut buf)?;
            let message = primitives::read_binary(&mut buf)?;
            Some(Will {
                topic,
                message,
                qos: will_qos,
                retain: will_retain,
            })
        } else {
            None
        };

        let username = if username_flag {
            Some(primitives::read_string(&mut buf)?)
        } else {
            None
        };

        let password = if password_flag {
            Some(primitives::read_binary(&mut buf)?)
        } else {
            None
        };

        // Every payload field the flags announced has been read, so nothing may remain
        if !buf.is_empty() {
            return Err(DecodeError::TrailingBytes { count: buf.len() });
        }

        Ok(Connect {
            clean_session,
            keep_alive,
            client_id,
            will,
            username,
            password,
        })
    }

    fn connect_flags(&self) -> u8 {
        // See the bit layout in decode_body [MQTT-3.1.2.3]
        let mut flags = 0u8;
        if self.clean_session {
            flags |= 1 << 1;
        }
        if let Some(will) = &self.will {
            flags |= 1 << 2;
            flags |= (will.qos as u8) << 3;
            if will.retain {
                flags |= 1 << 5;
            }
        }
        if self.password.is_some() {
            flags |= 1 << 6;
        }
        if self.username.is_some() {
            flags |= 1 << 7;
        }
        flags
    }

    /// `Option<Will>` already makes the will flag / retain / QoS combination correct by
    /// construction, leaving only password's dependency on username to check [MQTT-3.1.2-22]
    fn validate(&self) -> Result<(), EncodeError> {
        if self.username.is_none() && self.password.is_some() {
            return Err(EncodeError::InvalidState {
                reason: "password requires username",
            });
        }
        Ok(())
    }
}

/// CONNACK return code indicating the result of a connection attempt [MQTT-3.2.2.3]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConnectReturnCode {
    /// 0x00 — Connection accepted
    Accepted = 0x00,
    /// 0x01 — Unacceptable protocol version
    UnacceptableProtocol = 0x01,
    /// 0x02 — Client identifier rejected
    IdentifierRejected = 0x02,
    /// 0x03 — Server unavailable
    ServerUnavailable = 0x03,
    /// 0x04 — Bad username or password
    BadCredentials = 0x04,
    /// 0x05 — Not authorized
    NotAuthorized = 0x05,
}

impl TryFrom<u8> for ConnectReturnCode {
    type Error = DecodeError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0x00 => Ok(Self::Accepted),
            0x01 => Ok(Self::UnacceptableProtocol),
            0x02 => Ok(Self::IdentifierRejected),
            0x03 => Ok(Self::ServerUnavailable),
            0x04 => Ok(Self::BadCredentials),
            0x05 => Ok(Self::NotAuthorized),
            _ => Err(DecodeError::ProtocolError {
                reason: "invalid connect return code",
            }),
        }
    }
}

/// CONNACK packet — broker's response to a CONNECT request [MQTT-3.2]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConnAck {
    /// Whether the broker has a stored session for this client
    pub session_present: bool,
    /// Result of the connection attempt
    pub return_code: ConnectReturnCode,
}

impl ConnAck {
    /// Fixed header flags are always 0b0000 [MQTT-2.2.2, Table 2.2]
    const FLAGS: u8 = 0b0000;

    /// Body: ack_flags(1) + return_code(1) [MQTT-3.2.2]
    const BODY_LEN: usize = 2;

    pub(super) fn flags(&self) -> u8 {
        Self::FLAGS
    }

    pub(super) fn encoded_body_len(&self) -> usize {
        Self::BODY_LEN
    }

    pub(super) fn encode_body(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
        // Acknowledge flags byte: bit 0 is session present, bits 7-1 reserved
        primitives::write_u8(u8::from(self.session_present), buf);
        primitives::write_u8(self.return_code as u8, buf);
        Ok(())
    }

    pub(super) fn decode_body(header_flags: u8, mut buf: Bytes) -> Result<Self, DecodeError> {
        if header_flags != Self::FLAGS {
            return Err(DecodeError::InvalidFlags {
                packet_type: PacketType::ConnAck,
                flags: header_flags,
            });
        }

        let ack_flags = primitives::read_u8(&mut buf)?;
        // Only bit 0 is defined; bits 7-1 are reserved and must be 0 [MQTT-3.2.2.1]
        if ack_flags & 0xFE != 0 {
            return Err(DecodeError::ProtocolError {
                reason: "CONNACK acknowledge flags bits 7-1 must be 0",
            });
        }
        let return_code = ConnectReturnCode::try_from(primitives::read_u8(&mut buf)?)?;
        // The body is defined as exactly these two bytes [MQTT-3.2.2]
        if !buf.is_empty() {
            return Err(DecodeError::TrailingBytes { count: buf.len() });
        }

        Ok(ConnAck {
            session_present: ack_flags & 0x01 == 1,
            return_code,
        })
    }
}

/// DISCONNECT packet — client signals a clean disconnection [MQTT-3.14]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Disconnect;

impl Disconnect {
    /// Fixed header flags are always 0b0000 [MQTT-2.2.2, Table 2.2]
    const FLAGS: u8 = 0b0000;

    pub(super) fn flags(&self) -> u8 {
        Self::FLAGS
    }

    pub(super) fn encoded_body_len(&self) -> usize {
        0
    }

    pub(super) fn encode_body(&self, _buf: &mut BytesMut) -> Result<(), EncodeError> {
        Ok(())
    }

    pub(super) fn decode_body(header_flags: u8, buf: Bytes) -> Result<Self, DecodeError> {
        if header_flags != Self::FLAGS {
            return Err(DecodeError::InvalidFlags {
                packet_type: PacketType::Disconnect,
                flags: header_flags,
            });
        }
        // DISCONNECT has no variable header and no payload [MQTT-3.14.1]
        if !buf.is_empty() {
            return Err(DecodeError::TrailingBytes { count: buf.len() });
        }
        Ok(Self)
    }
}

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

    use super::*;
    use crate::v3::Packet;
    use crate::{DecodeError, EncodeError, PacketType, QoS};

    /// Helper: encode a v3::Packet and decode it back
    fn roundtrip(packet: Packet) -> Packet {
        let mut buf = BytesMut::new();
        packet.encode(&mut buf).unwrap();
        Packet::decode(&mut buf).unwrap().unwrap()
    }

    #[test]
    fn connect_minimal() {
        let pkt = Packet::Connect(Connect {
            clean_session: true,
            keep_alive: 0,
            client_id: String::new(),
            will: None,
            username: None,
            password: None,
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn connect_full() {
        let pkt = Packet::Connect(Connect {
            clean_session: false,
            keep_alive: 60,
            client_id: "my-client".to_owned(),
            will: Some(Will {
                topic: "will/topic".to_owned(),
                message: Bytes::from_static(b"bye"),
                qos: QoS::ExactlyOnce,
                retain: true,
            }),
            username: Some("user".to_owned()),
            password: Some(Bytes::from_static(b"pass")),
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn connect_will_qos0_no_retain() {
        let pkt = Packet::Connect(Connect {
            clean_session: true,
            keep_alive: 30,
            client_id: "c".to_owned(),
            will: Some(Will {
                topic: "t".to_owned(),
                message: Bytes::from_static(b"m"),
                qos: QoS::AtMostOnce,
                retain: false,
            }),
            username: None,
            password: None,
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn connect_username_only() {
        let pkt = Packet::Connect(Connect {
            clean_session: true,
            keep_alive: 10,
            client_id: "c".to_owned(),
            will: None,
            username: Some("admin".to_owned()),
            password: None,
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn connect_encode_password_without_username() {
        let pkt = Packet::Connect(Connect {
            clean_session: true,
            keep_alive: 10,
            client_id: "c".to_owned(),
            will: None,
            username: None,
            password: Some(Bytes::from_static(b"secret")),
        });
        let mut buf = BytesMut::new();
        assert_eq!(
            pkt.encode(&mut buf),
            Err(EncodeError::InvalidState {
                reason: "password requires username"
            })
        );
    }

    #[test]
    fn connect_decode_wrong_protocol_name() {
        // Manually build a CONNECT with protocol name "MQIsdp"
        let buf = build_connect_bytes(|b| {
            primitives::write_string("MQIsdp", b).unwrap();
            primitives::write_u8(PROTOCOL_LEVEL, b);
            primitives::write_u8(0x02, b); // clean_session
            primitives::write_u16(60, b);
            primitives::write_string("c", b).unwrap();
        });
        assert_eq!(
            Connect::decode_body(0x00, buf),
            Err(DecodeError::ProtocolError {
                reason: "protocol name must be \"MQTT\""
            })
        );
    }

    #[test]
    fn connect_decode_wrong_protocol_level() {
        let buf = build_connect_bytes(|b| {
            primitives::write_string("MQTT", b).unwrap();
            primitives::write_u8(5, b); // wrong level
            primitives::write_u8(0x02, b);
            primitives::write_u16(60, b);
            primitives::write_string("c", b).unwrap();
        });
        assert_eq!(
            Connect::decode_body(0x00, buf),
            Err(DecodeError::ProtocolError {
                reason: "protocol level must be 4 for MQTT 3.1.1"
            })
        );
    }

    #[test]
    fn connect_decode_reserved_bit_set() {
        let buf = build_connect_bytes(|b| {
            primitives::write_string("MQTT", b).unwrap();
            primitives::write_u8(PROTOCOL_LEVEL, b);
            primitives::write_u8(0x03, b); // bit0=1 (reserved)
            primitives::write_u16(60, b);
            primitives::write_string("c", b).unwrap();
        });
        assert_eq!(
            Connect::decode_body(0x00, buf),
            Err(DecodeError::ProtocolError {
                reason: "connect flags reserved bit must be 0"
            })
        );
    }

    #[test]
    fn connect_decode_will_qos_nonzero_without_will_flag() {
        // will_flag=0, will_qos=1 → flags byte = 0b0000_1000 | clean_session = 0b0000_1010
        let buf = build_connect_bytes(|b| {
            primitives::write_string("MQTT", b).unwrap();
            primitives::write_u8(PROTOCOL_LEVEL, b);
            primitives::write_u8(0x0A, b); // clean_session=1, will_flag=0, will_qos=1
            primitives::write_u16(60, b);
            primitives::write_string("c", b).unwrap();
        });
        assert_eq!(
            Connect::decode_body(0x00, buf),
            Err(DecodeError::ProtocolError {
                reason: "will_qos must be 0 when will_flag is 0"
            })
        );
    }

    #[test]
    fn connect_decode_will_retain_without_will_flag() {
        // will_flag=0, will_retain=1 → flags byte = 0b0010_0010
        let buf = build_connect_bytes(|b| {
            primitives::write_string("MQTT", b).unwrap();
            primitives::write_u8(PROTOCOL_LEVEL, b);
            primitives::write_u8(0x22, b); // clean_session=1, will_flag=0, will_retain=1
            primitives::write_u16(60, b);
            primitives::write_string("c", b).unwrap();
        });
        assert_eq!(
            Connect::decode_body(0x00, buf),
            Err(DecodeError::ProtocolError {
                reason: "will_retain must be 0 when will_flag is 0"
            })
        );
    }

    #[test]
    fn connect_decode_password_without_username() {
        // password_flag=1, username_flag=0 → flags = 0b0100_0010
        let buf = build_connect_bytes(|b| {
            primitives::write_string("MQTT", b).unwrap();
            primitives::write_u8(PROTOCOL_LEVEL, b);
            primitives::write_u8(0x42, b); // password=1, username=0, clean_session=1
            primitives::write_u16(60, b);
            primitives::write_string("c", b).unwrap();
            primitives::write_binary(b"pass", b).unwrap();
        });
        assert_eq!(
            Connect::decode_body(0x00, buf),
            Err(DecodeError::ProtocolError {
                reason: "password_flag=1 requires username_flag=1"
            })
        );
    }

    #[test]
    fn connect_decode_trailing_bytes() {
        let buf = build_connect_bytes(|b| {
            primitives::write_string("MQTT", b).unwrap();
            primitives::write_u8(PROTOCOL_LEVEL, b);
            primitives::write_u8(0x02, b); // clean_session only
            primitives::write_u16(60, b);
            primitives::write_string("c", b).unwrap();
            b.extend_from_slice(&[0xFF]); // trailing junk
        });
        assert_eq!(
            Connect::decode_body(0x00, buf),
            Err(DecodeError::TrailingBytes { count: 1 })
        );
    }

    #[test]
    fn connect_decode_invalid_header_flags() {
        let buf = Bytes::from_static(&[]);
        assert_eq!(
            Connect::decode_body(0x01, buf),
            Err(DecodeError::InvalidFlags {
                packet_type: PacketType::Connect,
                flags: 0x01,
            })
        );
    }

    #[test]
    fn connack_accepted_no_session() {
        let pkt = Packet::ConnAck(ConnAck {
            session_present: false,
            return_code: ConnectReturnCode::Accepted,
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn connack_accepted_session_present() {
        let pkt = Packet::ConnAck(ConnAck {
            session_present: true,
            return_code: ConnectReturnCode::Accepted,
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn connack_all_return_codes() {
        let codes = [
            ConnectReturnCode::Accepted,
            ConnectReturnCode::UnacceptableProtocol,
            ConnectReturnCode::IdentifierRejected,
            ConnectReturnCode::ServerUnavailable,
            ConnectReturnCode::BadCredentials,
            ConnectReturnCode::NotAuthorized,
        ];
        for code in codes {
            let pkt = Packet::ConnAck(ConnAck {
                session_present: false,
                return_code: code,
            });
            assert_eq!(roundtrip(pkt.clone()), pkt);
        }
    }

    #[test]
    fn connack_invalid_return_code() {
        let buf = Bytes::from_static(&[0x00, 0x06]); // ack_flags=0, return_code=6
        assert_eq!(
            ConnAck::decode_body(0x00, buf),
            Err(DecodeError::ProtocolError {
                reason: "invalid connect return code"
            })
        );
    }

    #[test]
    fn connack_invalid_flags() {
        let buf = Bytes::from_static(&[0x00, 0x00]);
        assert_eq!(
            ConnAck::decode_body(0x01, buf),
            Err(DecodeError::InvalidFlags {
                packet_type: PacketType::ConnAck,
                flags: 0x01,
            })
        );
    }

    #[test]
    fn connack_trailing_bytes() {
        let buf = Bytes::from_static(&[0x00, 0x00, 0xFF]); // extra byte
        assert_eq!(
            ConnAck::decode_body(0x00, buf),
            Err(DecodeError::TrailingBytes { count: 1 })
        );
    }

    #[test]
    fn connack_ack_flags_high_bits_set() {
        let buf = Bytes::from_static(&[0x02, 0x00]); // bit1 set in ack_flags
        assert_eq!(
            ConnAck::decode_body(0x00, buf),
            Err(DecodeError::ProtocolError {
                reason: "CONNACK acknowledge flags bits 7-1 must be 0"
            })
        );
    }

    #[test]
    fn disconnect_roundtrip() {
        let pkt = Packet::Disconnect(Disconnect);
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn disconnect_encode_bytes() {
        let mut buf = BytesMut::new();
        Packet::Disconnect(Disconnect).encode(&mut buf).unwrap();
        assert_eq!(&buf[..], &[0xE0, 0x00]);
    }

    #[test]
    fn disconnect_invalid_flags() {
        assert_eq!(
            Disconnect::decode_body(0x01, Bytes::new()),
            Err(DecodeError::InvalidFlags {
                packet_type: PacketType::Disconnect,
                flags: 0x01,
            })
        );
    }

    #[test]
    fn disconnect_trailing_bytes() {
        let buf = Bytes::from_static(&[0xFF]);
        assert_eq!(
            Disconnect::decode_body(0x00, buf),
            Err(DecodeError::TrailingBytes { count: 1 })
        );
    }

    fn build_connect_bytes(f: impl FnOnce(&mut BytesMut)) -> Bytes {
        let mut buf = BytesMut::new();
        f(&mut buf);
        buf.freeze()
    }
}