mqtt-protocol-core 0.7.7

A Sans-I/O style MQTT protocol library for Rust that supports both MQTT v5.0 and v3.1.1.
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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
// MIT License
//
// Copyright (c) 2025 Takatoshi Kondo
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use alloc::vec::Vec;
use core::fmt;
use derive_builder::Builder;
#[cfg(feature = "std")]
use std::io::IoSlice;

use serde::ser::{SerializeStruct, Serializer};
use serde::Serialize;

use getset::{CopyGetters, Getters};

use crate::mqtt::packet::packet_type::{FixedHeader, PacketType};
use crate::mqtt::packet::property::PropertiesToContinuousBuffer;
use crate::mqtt::packet::variable_byte_integer::VariableByteInteger;
use crate::mqtt::packet::GenericPacketDisplay;
use crate::mqtt::packet::GenericPacketTrait;
#[cfg(feature = "std")]
use crate::mqtt::packet::PropertiesToBuffers;
use crate::mqtt::packet::{Properties, PropertiesParse, PropertiesSize, Property};
use crate::mqtt::result_code::DisconnectReasonCode;
use crate::mqtt::result_code::MqttError;

/// MQTT 5.0 DISCONNECT packet representation
///
/// The DISCONNECT packet is sent by either the client or the server to indicate
/// graceful disconnection from the MQTT connection. In MQTT 5.0, both the client
/// and server can send DISCONNECT packets to cleanly terminate the connection.
///
/// According to MQTT 5.0 specification, the DISCONNECT packet contains:
/// - Fixed header with packet type and remaining length
/// - Variable header with reason code and properties (both optional)
/// - No payload
///
/// # Reason Codes
///
/// The reason code indicates why the connection is being terminated:
/// - `0x00` Normal disconnection - Clean disconnect without error
/// - `0x04` Disconnect with Will Message - Normal disconnect, publish Will Message
/// - `0x80` Unspecified error
/// - `0x81` Malformed packet
/// - `0x82` Protocol error
/// - `0x83` Implementation specific error
/// - `0x87` Not authorized
/// - `0x89` Server busy
/// - `0x8B` Server shutting down
/// - `0x8D` Keep alive timeout
/// - `0x8E` Session taken over
/// - `0x8F` Topic filter invalid
/// - `0x90` Topic name invalid
/// - `0x93` Receive maximum exceeded
/// - `0x94` Topic alias invalid
/// - `0x95` Packet too large
/// - `0x96` Message rate too high
/// - `0x97` Quota exceeded
/// - `0x98` Administrative action
/// - `0x99` Payload format invalid
/// - `0x9A` Retain not supported
/// - `0x9B` QoS not supported
/// - `0x9C` Use another server
/// - `0x9D` Server moved
/// - `0x9E` Shared subscriptions not supported
/// - `0x9F` Connection rate exceeded
/// - `0xA0` Maximum connect time
/// - `0xA1` Subscription identifiers not supported
/// - `0xA2` Wildcard subscriptions not supported
///
/// # Properties
///
/// MQTT 5.0 DISCONNECT packets can include the following properties:
/// - **Session Expiry Interval**: Overrides the session expiry interval set in CONNECT
/// - **Reason String**: Human-readable string describing the reason for disconnect
/// - **User Properties**: Key-value pairs for application-specific metadata
/// - **Server Reference**: Alternative server for client to connect to
///
/// # Packet Structure Rules
///
/// - If no reason code is present, the remaining length is 0
/// - If reason code is present but no properties, remaining length is 1
/// - If properties are present, reason code must also be present
/// - Properties must not contain duplicate entries except for User Properties
///
/// # Examples
///
/// ```ignore
/// use mqtt_protocol_core::mqtt;
/// use mqtt_protocol_core::mqtt::result_code::DisconnectReasonCode;
///
/// // Create a simple normal disconnection
/// let disconnect = mqtt::packet::v5_0::Disconnect::builder()
///     .build()
///     .unwrap();
///
/// // Create disconnect with reason code
/// let disconnect = mqtt::packet::v5_0::Disconnect::builder()
///     .reason_code(DisconnectReasonCode::NormalDisconnection)
///     .build()
///     .unwrap();
///
/// assert_eq!(disconnect.reason_code(), Some(DisconnectReasonCode::NormalDisconnection));
///
/// // Create disconnect with reason code and properties
/// let props = vec![
///     mqtt::packet::ReasonString::new("Session timeout").unwrap().into(),
///     mqtt::packet::UserProperty::new("client_id", "device123").unwrap().into(),
/// ];
/// let disconnect = mqtt::packet::v5_0::Disconnect::builder()
///     .reason_code(DisconnectReasonCode::KeepAliveTimeout)
///     .props(props)
///     .build()
///     .unwrap();
///
/// // Serialize to bytes for network transmission
/// let buffers = disconnect.to_buffers();
/// let size = disconnect.size();
/// ```
#[derive(PartialEq, Eq, Builder, Clone, Getters, CopyGetters)]
#[builder(no_std, derive(Debug), pattern = "owned", setter(into), build_fn(skip))]
pub struct Disconnect {
    #[builder(private)]
    fixed_header: [u8; 1],
    #[builder(private)]
    remaining_length: VariableByteInteger,
    #[builder(private)]
    reason_code_buf: Option<[u8; 1]>,
    #[builder(private)]
    property_length: Option<VariableByteInteger>,

    /// Optional MQTT 5.0 properties for the DISCONNECT packet
    ///
    /// Properties provide additional metadata about the disconnection.
    /// Valid properties for DISCONNECT packets include:
    /// - Session Expiry Interval
    /// - Reason String
    /// - User Properties
    /// - Server Reference
    #[builder(setter(into, strip_option))]
    #[getset(get = "pub")]
    pub props: Option<Properties>,
}

impl Disconnect {
    /// Creates a new builder for constructing a DISCONNECT packet
    ///
    /// The builder pattern allows for flexible construction of DISCONNECT packets
    /// with optional reason codes and properties.
    ///
    /// # Returns
    ///
    /// A new `DisconnectBuilder` instance
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    ///
    /// let disconnect = mqtt::packet::v5_0::Disconnect::builder()
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn builder() -> DisconnectBuilder {
        DisconnectBuilder::default()
    }

    /// Returns the packet type for DISCONNECT packets
    ///
    /// This is always `PacketType::Disconnect` (14) for DISCONNECT packets.
    ///
    /// # Returns
    ///
    /// `PacketType::Disconnect`
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    /// use mqtt_protocol_core::mqtt::packet::packet_type::PacketType;
    ///
    /// assert_eq!(mqtt::packet::v5_0::Disconnect::packet_type(), PacketType::Disconnect);
    /// ```
    pub fn packet_type() -> PacketType {
        PacketType::Disconnect
    }

    /// Returns the reason code for the disconnection
    ///
    /// The reason code indicates why the connection is being terminated.
    /// If no reason code is present in the packet, `None` is returned,
    /// which implies normal disconnection (0x00).
    ///
    /// # Returns
    ///
    /// - `Some(DisconnectReasonCode)` if a reason code is present
    /// - `None` if no reason code is present (implies normal disconnection)
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    /// use mqtt_protocol_core::mqtt::result_code::DisconnectReasonCode;
    ///
    /// // Disconnect without explicit reason code
    /// let disconnect = mqtt::packet::v5_0::Disconnect::builder()
    ///     .build()
    ///     .unwrap();
    /// assert_eq!(disconnect.reason_code(), None);
    ///
    /// // Disconnect with reason code
    /// let disconnect = mqtt::packet::v5_0::Disconnect::builder()
    ///     .reason_code(DisconnectReasonCode::ServerShuttingDown)
    ///     .build()
    ///     .unwrap();
    /// assert_eq!(disconnect.reason_code(), Some(DisconnectReasonCode::ServerShuttingDown));
    /// ```
    pub fn reason_code(&self) -> Option<DisconnectReasonCode> {
        self.reason_code_buf
            .as_ref()
            .and_then(|buf| DisconnectReasonCode::try_from(buf[0]).ok())
    }

    /// Returns the total size of the DISCONNECT packet in bytes
    ///
    /// This includes the fixed header (1 byte), remaining length field,
    /// optional reason code (1 byte), optional property length field,
    /// and optional properties.
    ///
    /// # Returns
    ///
    /// The total packet size in bytes
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    /// use mqtt_protocol_core::mqtt::result_code::DisconnectReasonCode;
    ///
    /// // Simple disconnect (2 bytes: fixed header + remaining length 0)
    /// let disconnect = mqtt::packet::v5_0::Disconnect::builder()
    ///     .build()
    ///     .unwrap();
    /// let size = disconnect.size();
    ///
    /// // Disconnect with reason code (4 bytes: fixed header + remaining length 1 + reason code + property length 0)
    /// let disconnect = mqtt::packet::v5_0::Disconnect::builder()
    ///     .reason_code(DisconnectReasonCode::NormalDisconnection)
    ///     .build()
    ///     .unwrap();
    /// let size_with_reason = disconnect.size();
    /// assert!(size_with_reason > size);
    /// ```
    pub fn size(&self) -> usize {
        1 + self.remaining_length.size() + self.remaining_length.to_u32() as usize
    }

    /// Create IoSlice buffers for efficient network I/O
    ///
    /// Returns a vector of `IoSlice` objects that can be used for vectored I/O
    /// operations, allowing zero-copy writes to network sockets. The buffers
    /// represent the complete DISCONNECT packet in wire format.
    ///
    /// # Returns
    ///
    /// A vector of `IoSlice` objects for vectored I/O operations
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    /// use mqtt_protocol_core::mqtt::result_code::DisconnectReasonCode;
    ///
    /// let disconnect = mqtt::packet::v5_0::Disconnect::builder()
    ///     .reason_code(DisconnectReasonCode::NormalDisconnection)
    ///     .build()
    ///     .unwrap();
    ///
    /// let buffers = disconnect.to_buffers();
    /// // Use with vectored write: socket.write_vectored(&buffers)?;
    /// ```
    #[cfg(feature = "std")]
    pub fn to_buffers(&self) -> Vec<IoSlice<'_>> {
        let mut bufs = Vec::new();
        bufs.push(IoSlice::new(&self.fixed_header));
        bufs.push(IoSlice::new(self.remaining_length.as_bytes()));
        if let Some(buf) = &self.reason_code_buf {
            bufs.push(IoSlice::new(buf));
        }
        if let Some(pl) = &self.property_length {
            bufs.push(IoSlice::new(pl.as_bytes()));
        }
        if let Some(ref props) = self.props {
            bufs.append(&mut props.to_buffers());
        }

        bufs
    }

    /// Create a continuous buffer containing the complete packet data
    ///
    /// Returns a vector containing all packet bytes in a single continuous buffer.
    /// This method provides an alternative to `to_buffers()` for no-std environments
    /// where vectored I/O is not available.
    ///
    /// The returned buffer contains the complete DISCONNECT packet serialized according
    /// to the MQTT v5.0 protocol specification, including fixed header, remaining
    /// length, optional reason code, and optional properties.
    ///
    /// # Returns
    ///
    /// A vector containing the complete packet data
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    ///
    /// let disconnect = mqtt::packet::v5_0::Disconnect::new();
    /// let buffer = disconnect.to_continuous_buffer();
    /// // buffer contains all packet bytes
    /// ```
    ///
    /// [`to_buffers()`]: #method.to_buffers
    pub fn to_continuous_buffer(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        buf.extend_from_slice(&self.fixed_header);
        buf.extend_from_slice(self.remaining_length.as_bytes());
        if let Some(rc_buf) = &self.reason_code_buf {
            buf.extend_from_slice(rc_buf);
        }
        if let Some(pl) = &self.property_length {
            buf.extend_from_slice(pl.as_bytes());
        }
        if let Some(ref props) = self.props {
            buf.append(&mut props.to_continuous_buffer());
        }
        buf
    }

    /// Parses a DISCONNECT packet from byte data
    ///
    /// This method parses the variable header portion of a DISCONNECT packet,
    /// extracting the optional reason code and properties. The fixed header
    /// should have been parsed separately before calling this method.
    ///
    /// # Parameters
    ///
    /// * `data` - Byte slice containing the variable header data
    ///
    /// # Returns
    ///
    /// * `Ok((Disconnect, usize))` - The parsed packet and number of bytes consumed
    /// * `Err(MqttError)` - If the packet is malformed or contains invalid data
    ///
    /// # Errors
    ///
    /// - `MqttError::MalformedPacket` - If the packet structure is invalid
    /// - `MqttError::ProtocolError` - If properties violate MQTT 5.0 rules
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    ///
    /// // Parse disconnect with reason code and empty properties
    /// let data = [0x00, 0x00]; // Normal disconnection + empty properties
    /// let (disconnect, consumed) = mqtt::packet::v5_0::Disconnect::parse(&data).unwrap();
    /// assert_eq!(consumed, 2);
    ///
    /// // Parse empty disconnect (no reason code, no properties)
    /// let data = [];
    /// let (disconnect, consumed) = mqtt::packet::v5_0::Disconnect::parse(&data).unwrap();
    /// assert_eq!(consumed, 0);
    /// ```
    pub fn parse(data: &[u8]) -> Result<(Self, usize), MqttError> {
        let mut cursor = 0;

        // reason_code
        let reason_code_buf = if cursor < data.len() {
            let rc = data[cursor];
            let _ = DisconnectReasonCode::try_from(rc).map_err(|_| MqttError::MalformedPacket)?;
            cursor += 1;
            Some([rc])
        } else {
            None
        };

        // properties
        let (property_length, props) = if reason_code_buf.is_some() && cursor < data.len() {
            let (props, consumed) = Properties::parse(&data[cursor..])?;
            cursor += consumed;
            validate_disconnect_properties(&props)?;
            let prop_len = VariableByteInteger::from_u32(props.size() as u32).unwrap();

            (Some(prop_len), Some(props))
        } else {
            (None, None)
        };

        let remaining_size = reason_code_buf.as_ref().map_or(0, |_| 1)
            + property_length.as_ref().map_or(0, |pl| pl.size())
            + props.as_ref().map_or(0, |ps| ps.size());

        let disconnect = Disconnect {
            fixed_header: [FixedHeader::Disconnect.as_u8()],
            remaining_length: VariableByteInteger::from_u32(remaining_size as u32).unwrap(),
            reason_code_buf,
            property_length,
            props,
        };

        Ok((disconnect, cursor))
    }
}

/// Builder for constructing DISCONNECT packets
///
/// The `DisconnectBuilder` follows the builder pattern to allow flexible
/// construction of DISCONNECT packets with optional components.
///
/// # Validation Rules
///
/// - Properties can only be set if a reason code is also present
/// - Properties must contain only valid DISCONNECT properties
/// - No duplicate properties are allowed (except User Properties)
///
/// # Examples
///
/// ```ignore
/// use mqtt_protocol_core::mqtt;
/// use mqtt_protocol_core::mqtt::result_code::DisconnectReasonCode;
///
/// let disconnect = mqtt::packet::v5_0::Disconnect::builder()
///     .reason_code(DisconnectReasonCode::ServerShuttingDown)
///     .props(vec![
///         mqtt::packet::ReasonString::new("Maintenance").unwrap().into()
///     ])
///     .build()
///     .unwrap();
/// ```
impl DisconnectBuilder {
    /// Sets the reason code for the DISCONNECT packet
    ///
    /// The reason code indicates why the connection is being terminated.
    /// Setting a reason code is required if you want to include properties.
    ///
    /// # Parameters
    ///
    /// * `rc` - The disconnect reason code
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    /// use mqtt_protocol_core::mqtt::result_code::DisconnectReasonCode;
    ///
    /// let disconnect = mqtt::packet::v5_0::Disconnect::builder()
    ///     .reason_code(DisconnectReasonCode::KeepAliveTimeout)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn reason_code(mut self, rc: DisconnectReasonCode) -> Self {
        self.reason_code_buf = Some(Some([rc as u8]));
        self
    }

    /// Validates the builder configuration before building the packet
    ///
    /// This method ensures that the packet configuration follows MQTT 5.0 rules:
    /// - Properties can only be present if a reason code is also present
    /// - Properties must be valid for DISCONNECT packets
    ///
    /// # Returns
    ///
    /// * `Ok(())` if the configuration is valid
    /// * `Err(MqttError)` if validation fails
    ///
    /// # Errors
    ///
    /// - `MqttError::MalformedPacket` - If properties are set without a reason code
    /// - `MqttError::ProtocolError` - If properties contain invalid entries
    fn validate(&self) -> Result<(), MqttError> {
        if self.reason_code_buf.is_none() && self.props.is_some() {
            return Err(MqttError::MalformedPacket);
        }
        if let Some(inner_option) = &self.props {
            let props = inner_option
                .as_ref()
                .expect("INTERNAL ERRORS: props was set with None value, this should never happen");
            validate_disconnect_properties(props)?;
        }
        Ok(())
    }

    /// Builds the DISCONNECT packet from the configured parameters
    ///
    /// This method validates the builder configuration and constructs the final
    /// DISCONNECT packet. It calculates the remaining length and organizes
    /// all components according to MQTT 5.0 specification.
    ///
    /// # Returns
    ///
    /// * `Ok(Disconnect)` - The constructed packet
    /// * `Err(MqttError)` - If the configuration is invalid
    ///
    /// # Errors
    ///
    /// - `MqttError::MalformedPacket` - If the packet structure would be invalid
    /// - `MqttError::ProtocolError` - If properties violate MQTT 5.0 rules
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    /// use mqtt_protocol_core::mqtt::result_code::DisconnectReasonCode;
    ///
    /// let result = mqtt::packet::v5_0::Disconnect::builder()
    ///     .reason_code(DisconnectReasonCode::NormalDisconnection)
    ///     .build();
    ///
    /// match result {
    ///     Ok(disconnect) => println!("Packet built successfully"),
    ///     Err(e) => println!("Build failed: {:?}", e),
    /// }
    /// ```
    pub fn build(self) -> Result<Disconnect, MqttError> {
        self.validate()?;

        let reason_code_buf = self.reason_code_buf.flatten();
        let props = self.props.flatten();
        let props_size: usize = props.as_ref().map_or(0, |p| p.size());
        // property_length only if properties are present
        let property_length = if props.is_some() {
            Some(VariableByteInteger::from_u32(props_size as u32).unwrap())
        } else {
            None
        };

        let mut remaining = 0;
        // add reason code if present
        if reason_code_buf.is_some() {
            remaining += 1;
        }
        // add properties if present
        if let Some(ref pl) = property_length {
            remaining += pl.size() + props_size;
        }
        let remaining_length = VariableByteInteger::from_u32(remaining as u32).unwrap();

        Ok(Disconnect {
            fixed_header: [FixedHeader::Disconnect.as_u8()],
            remaining_length,
            reason_code_buf,
            property_length,
            props,
        })
    }
}

/// Implements JSON serialization for DISCONNECT packets
///
/// This implementation converts the DISCONNECT packet to a JSON representation
/// suitable for debugging, logging, or API responses. The serialization includes
/// the packet type, optional reason code, and optional properties.
///
/// # JSON Structure
///
/// ```json
/// {
///   "type": "disconnect",
///   "reason_code": "NormalDisconnection",  // Optional
///   "props": [ ... ]                        // Optional
/// }
/// ```
///
/// # Examples
///
/// ```ignore
/// use mqtt_protocol_core::mqtt;
/// use mqtt_protocol_core::mqtt::result_code::DisconnectReasonCode;
///
/// let disconnect = mqtt::packet::v5_0::Disconnect::builder()
///     .reason_code(DisconnectReasonCode::ServerShuttingDown)
///     .build()
///     .unwrap();
///
/// let json = serde_json::to_string(&disconnect).unwrap();
/// println!("DISCONNECT packet: {}", json);
/// ```
impl Serialize for Disconnect {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut field_count = 1; // type

        if self.reason_code_buf.is_some() {
            field_count += 1; // reason_code
        }

        if self.props.is_some() {
            field_count += 1; // props
        }

        let mut state = serializer.serialize_struct("disconnect", field_count)?;
        state.serialize_field("type", PacketType::Disconnect.as_str())?;
        if self.reason_code_buf.is_some() {
            state.serialize_field("reason_code", &self.reason_code())?;
        }
        if let Some(props) = &self.props {
            state.serialize_field("props", props)?;
        }

        state.end()
    }
}

/// Implements `Display` trait for DISCONNECT packets
///
/// This provides a human-readable JSON representation of the packet,
/// making it useful for debugging and logging purposes.
///
/// # Examples
///
/// ```ignore
/// use mqtt_protocol_core::mqtt;
/// use mqtt_protocol_core::mqtt::result_code::DisconnectReasonCode;
///
/// let disconnect = mqtt::packet::v5_0::Disconnect::builder()
///     .reason_code(DisconnectReasonCode::NormalDisconnection)
///     .build()
///     .unwrap();
///
/// println!("Packet: {}", disconnect);
/// // Output: {"type":"disconnect","reason_code":"NormalDisconnection"}
/// ```
impl fmt::Display for Disconnect {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match serde_json::to_string(self) {
            Ok(json) => write!(f, "{json}"),
            Err(e) => write!(f, "{{\"error\": \"{e}\"}}"),
        }
    }
}

/// Implements `Debug` trait for DISCONNECT packets
///
/// This provides the same output as the `Display` implementation,
/// showing the JSON representation for debugging purposes.
///
/// # Examples
///
/// ```ignore
/// use mqtt_protocol_core::mqtt;
///
/// let disconnect = mqtt::packet::v5_0::Disconnect::builder()
///     .build()
///     .unwrap();
///
/// println!("{:?}", disconnect);
/// // Output: {"type":"disconnect"}
/// ```
impl fmt::Debug for Disconnect {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

/// Implements the generic packet trait for DISCONNECT packets
///
/// This trait provides a common interface for all MQTT packet types,
/// allowing them to be used polymorphically in packet processing code.
///
/// # Examples
///
/// ```ignore
/// use mqtt_protocol_core::mqtt;
/// use mqtt_protocol_core::mqtt::packet::GenericPacketTrait;
///
/// let disconnect = mqtt::packet::v5_0::Disconnect::builder()
///     .build()
///     .unwrap();
///
/// // Use through the generic trait
/// let size = disconnect.size();
/// let buffers = disconnect.to_buffers();
/// ```
impl GenericPacketTrait for Disconnect {
    fn size(&self) -> usize {
        self.size()
    }

    #[cfg(feature = "std")]
    fn to_buffers(&self) -> Vec<IoSlice<'_>> {
        self.to_buffers()
    }

    fn to_continuous_buffer(&self) -> Vec<u8> {
        self.to_continuous_buffer()
    }
}

/// Implements the generic packet display trait for DISCONNECT packets
///
/// This trait provides a common display interface for all MQTT packet types,
/// enabling consistent formatting across different packet implementations.
///
/// # Examples
///
/// ```ignore
/// use mqtt_protocol_core::mqtt;
/// use mqtt_protocol_core::mqtt::packet::GenericPacketDisplay;
///
/// let disconnect = mqtt::packet::v5_0::Disconnect::builder()
///     .build()
///     .unwrap();
///
/// // Format through the generic trait
/// println!("{}", disconnect);
/// ```
impl GenericPacketDisplay for Disconnect {
    fn fmt_debug(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Debug::fmt(self, f)
    }

    fn fmt_display(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Display::fmt(self, f)
    }
}

/// Validates that properties are appropriate for DISCONNECT packets
///
/// This function ensures that only valid properties are included in DISCONNECT packets
/// and that no duplicates exist (except for User Properties which can appear multiple times).
///
/// # Valid Properties for DISCONNECT
///
/// - **Session Expiry Interval**: Maximum one occurrence
/// - **Reason String**: Maximum one occurrence
/// - **User Property**: Multiple occurrences allowed
/// - **Server Reference**: Maximum one occurrence
///
/// # Parameters
///
/// * `props` - Slice of properties to validate
///
/// # Returns
///
/// * `Ok(())` if all properties are valid
/// * `Err(MqttError::ProtocolError)` if invalid or duplicate properties are found
///
/// # Errors
///
/// - `MqttError::ProtocolError` - If properties contain invalid entries or duplicates
///
/// # Examples
///
/// ```ignore
/// use mqtt_protocol_core::mqtt;
///
/// let props = vec![
///     mqtt::packet::ReasonString::new("Timeout").unwrap().into(),
///     mqtt::packet::UserProperty::new("client", "device1").unwrap().into(),
/// ];
///
/// // This is called internally during packet construction
/// // validate_disconnect_properties(&props).unwrap();
/// ```
fn validate_disconnect_properties(props: &[Property]) -> Result<(), MqttError> {
    let mut count_session_expiry_interval = 0;
    let mut count_reason_string = 0;
    let mut count_server_reference = 0;
    for prop in props {
        match prop {
            Property::SessionExpiryInterval(_) => count_session_expiry_interval += 1,
            Property::ReasonString(_) => count_reason_string += 1,
            Property::UserProperty(_) => {}
            Property::ServerReference(_) => count_server_reference += 1,
            _ => return Err(MqttError::ProtocolError),
        }
    }
    if count_session_expiry_interval > 1 {
        return Err(MqttError::ProtocolError);
    }
    if count_reason_string > 1 {
        return Err(MqttError::ProtocolError);
    }
    if count_server_reference > 1 {
        return Err(MqttError::ProtocolError);
    }
    Ok(())
}