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
// 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::AuthReasonCode;
use crate::mqtt::result_code::MqttError;

/// MQTT v5.0 AUTH packet representation
///
/// The AUTH packet is sent from the Client to the Server or from the Server to the Client
/// as part of an extended authentication exchange, such as challenge/response authentication.
/// It is also used by the Client or Server to perform re-authentication during a connection.
///
/// The AUTH packet enables enhanced authentication flows beyond the basic username/password
/// mechanism provided in the CONNECT packet. It supports:
/// - SASL-based authentication mechanisms
/// - Challenge/response authentication flows
/// - Re-authentication during an active connection
/// - Custom authentication methods
///
/// # Packet Structure
///
/// The AUTH packet consists of:
/// - Fixed Header (1 byte): Packet type (0xF0) and flags
/// - Variable Header:
///   - Reason Code (1 byte, optional)
///   - Properties (variable length, optional if reason code present)
///
/// # Authentication Flow
///
/// Enhanced authentication is a challenge/response style authentication that can extend
/// beyond the initial connection. The flow typically involves:
/// 1. Client sends CONNECT with Authentication Method property
/// 2. Server responds with CONNACK containing Continue Authentication reason code
/// 3. Multiple AUTH packet exchanges between client and server
/// 4. Final CONNACK with Success or failure reason code
///
/// # Re-authentication
///
/// Either the Client or Server can initiate re-authentication at any time during the
/// connection by sending an AUTH packet with a reason code of Re-authenticate.
///
/// # Examples
///
/// ```ignore
/// use mqtt_protocol_core::mqtt;
/// use mqtt_protocol_core::mqtt::result_code::AuthReasonCode;
/// use mqtt_protocol_core::mqtt::packet::Properties;
/// use mqtt_protocol_core::mqtt::packet::Property;
///
/// // Create an AUTH packet for continue authentication
/// let auth = mqtt::packet::v5_0::Auth::builder()
///     .reason_code(AuthReasonCode::ContinueAuthentication)
///     .props(Properties::from_vec(vec![
///         Property::AuthenticationMethod("SCRAM-SHA-256".into()),
///         Property::AuthenticationData(b"challenge_data".to_vec()),
///     ]))
///     .build()
///     .unwrap();
///
/// // Create an AUTH packet for re-authentication
/// let reauth = mqtt::packet::v5_0::Auth::builder()
///     .reason_code(AuthReasonCode::ReAuthenticate)
///     .build()
///     .unwrap();
/// ```
#[derive(PartialEq, Eq, Builder, Clone, Getters, CopyGetters)]
#[builder(no_std, derive(Debug), pattern = "owned", setter(into), build_fn(skip))]
pub struct Auth {
    /// Fixed header containing packet type and flags
    #[builder(private)]
    fixed_header: [u8; 1],
    /// Remaining length of the variable header and payload
    #[builder(private)]
    remaining_length: VariableByteInteger,
    /// Reason code buffer (1 byte if present)
    #[builder(private)]
    reason_code_buf: Option<[u8; 1]>,
    /// Property length as variable byte integer
    #[builder(private)]
    property_length: Option<VariableByteInteger>,

    /// MQTT v5.0 properties for the AUTH packet
    ///
    /// Valid properties for AUTH packets include:
    /// - Authentication Method: Specifies the authentication method being used
    /// - Authentication Data: Contains method-specific authentication data
    /// - Reason String: Human-readable string describing the reason
    /// - User Property: Application-specific key-value pairs
    #[builder(setter(into, strip_option))]
    #[getset(get = "pub")]
    pub props: Option<Properties>,
}

impl Auth {
    /// Create a new AuthBuilder for constructing AUTH packets
    ///
    /// Returns a builder instance that can be used to configure and construct
    /// an AUTH packet with the desired properties and reason code.
    ///
    /// # Returns
    ///
    /// * `AuthBuilder` - A new builder instance
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    /// use mqtt_protocol_core::mqtt::result_code::AuthReasonCode;
    ///
    /// let auth = mqtt::packet::v5_0::Auth::builder()
    ///     .reason_code(AuthReasonCode::ContinueAuthentication)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn builder() -> AuthBuilder {
        AuthBuilder::default()
    }

    /// Get the packet type for AUTH packets
    ///
    /// Returns the fixed packet type identifier for AUTH packets as defined
    /// in the MQTT v5.0 specification.
    ///
    /// # Returns
    ///
    /// * `PacketType::Auth` - The AUTH packet type constant
    pub fn packet_type() -> PacketType {
        PacketType::Auth
    }

    /// Get the reason code from the AUTH packet
    ///
    /// Extracts and parses the reason code from the packet buffer. The reason code
    /// indicates the purpose or result of the authentication operation.
    ///
    /// # Returns
    ///
    /// * `Some(AuthReasonCode)` - The parsed reason code if present and valid
    /// * `None` - If no reason code is present in the packet
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    /// use mqtt_protocol_core::mqtt::result_code::AuthReasonCode;
    ///
    /// let auth = mqtt::packet::v5_0::Auth::builder()
    ///     .reason_code(AuthReasonCode::Success)
    ///     .build()
    ///     .unwrap();
    ///
    /// assert_eq!(auth.reason_code(), Some(AuthReasonCode::Success));
    /// ```
    pub fn reason_code(&self) -> Option<AuthReasonCode> {
        self.reason_code_buf
            .as_ref()
            .and_then(|buf| AuthReasonCode::try_from(buf[0]).ok())
    }

    /// Calculate the total size of the AUTH packet in bytes
    ///
    /// Returns the complete size of the packet including the fixed header,
    /// remaining length field, reason code (if present), property length
    /// (if present), and all properties.
    ///
    /// # Returns
    ///
    /// * `usize` - Total packet size in bytes
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    ///
    /// let auth = mqtt::packet::v5_0::Auth::builder().build().unwrap();
    /// let size = auth.size();
    /// println!("AUTH packet size: {} bytes", 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 AUTH packet in wire format.
    ///
    /// # Returns
    ///
    /// A vector of `IoSlice` objects for vectored I/O operations
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    ///
    /// let auth = mqtt::packet::v5_0::Auth::builder().build().unwrap();
    /// let buffers = auth.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 AUTH 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 auth = mqtt::packet::v5_0::Auth::builder().build().unwrap();
    /// let buffer = auth.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
    }

    /// Parse an AUTH packet from raw bytes
    ///
    /// Parses the variable header portion of an AUTH packet from the provided byte buffer.
    /// This function expects the fixed header to have already been parsed and removed.
    ///
    /// The parsing process validates:
    /// - Reason code validity (if present)
    /// - Property structure and content
    /// - Required property relationships (e.g., Authentication Data requires Authentication Method)
    /// - Protocol compliance for reason code and property combinations
    ///
    /// # Parameters
    ///
    /// * `data` - Byte slice containing the AUTH packet variable header (excluding fixed header)
    ///
    /// # Returns
    ///
    /// * `Ok((Auth, usize))` - Successfully parsed AUTH packet and number of bytes consumed
    /// * `Err(MqttError::MalformedPacket)` - If the packet structure is invalid
    /// * `Err(MqttError::ProtocolError)` - If the packet violates MQTT protocol rules
    ///
    /// # Protocol Rules
    ///
    /// - If reason code is not Success, Authentication Method property is required
    /// - Authentication Data property requires Authentication Method property
    /// - Properties must not contain duplicates (except User Property)
    /// - Only specific properties are allowed in AUTH packets
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    ///
    /// let data = &[0x00, 0x00]; // Minimal AUTH packet: Success reason code + empty properties
    /// let (auth_packet, consumed) = mqtt::packet::v5_0::Auth::parse(data)?;
    /// assert_eq!(consumed, 2);
    /// ```
    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 _ = AuthReasonCode::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;
            let prop_len = VariableByteInteger::from_u32(props.size() as u32).unwrap();

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

        // Validate the combination of reason code and properties
        let reason_code = reason_code_buf
            .as_ref()
            .and_then(|buf| AuthReasonCode::try_from(buf[0]).ok());
        validate_auth_packet(reason_code, &props)?;

        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 auth = Auth {
            fixed_header: [FixedHeader::Auth.as_u8()],
            remaining_length: VariableByteInteger::from_u32(remaining_size as u32).unwrap(),
            reason_code_buf,
            property_length,
            props,
        };

        Ok((auth, cursor))
    }
}

/// Builder implementation for AUTH packets
///
/// The `AuthBuilder` provides a fluent interface for constructing AUTH packets
/// with proper validation of MQTT v5.0 protocol requirements.
impl AuthBuilder {
    /// Validate the current builder state against MQTT protocol rules
    ///
    /// Performs comprehensive validation of the AUTH packet configuration to ensure
    /// it complies with MQTT v5.0 specification requirements.
    ///
    /// # Validation Rules
    ///
    /// - Properties cannot be present without a reason code
    /// - If reason code is not Success, Authentication Method property is required
    /// - Authentication Data property requires Authentication Method property
    /// - Properties must not contain invalid duplicates
    /// - Only valid properties are allowed in AUTH packets
    ///
    /// # Returns
    ///
    /// * `Ok(())` - If the configuration is valid
    /// * `Err(MqttError::MalformedPacket)` - If the packet structure is invalid
    /// * `Err(MqttError::ProtocolError)` - If the packet violates protocol rules
    fn validate(&self) -> Result<(), MqttError> {
        if self.reason_code_buf.is_none() && self.props.is_some() {
            return Err(MqttError::MalformedPacket);
        }
        if self.props.is_some() {
            // Properties validation is done in validate_auth_packet
        }

        // Validate the combination of reason code and properties
        let reason_code = self
            .reason_code_buf
            .as_ref()
            .and_then(|opt| opt.as_ref())
            .and_then(|buf| AuthReasonCode::try_from(buf[0]).ok());
        let props = self.props.as_ref().and_then(|p| p.as_ref()).cloned();
        validate_auth_packet(reason_code, &props)?;

        Ok(())
    }

    /// Set the reason code for the AUTH packet
    ///
    /// Sets the reason code that indicates the purpose or result of the authentication
    /// operation. When a reason code is set, empty properties are automatically added
    /// if no properties were previously configured.
    ///
    /// # Parameters
    ///
    /// * `rc` - The authentication reason code to set
    ///
    /// # Returns
    ///
    /// * `Self` - The builder instance for method chaining
    ///
    /// # Valid Reason Codes
    ///
    /// - `Success` (0x00): Authentication successful
    /// - `ContinueAuthentication` (0x18): Continue the authentication process
    /// - `ReAuthenticate` (0x19): Initiate re-authentication
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    /// use mqtt_protocol_core::mqtt::result_code::AuthReasonCode;
    ///
    /// let auth = mqtt::packet::v5_0::Auth::builder()
    ///     .reason_code(AuthReasonCode::ContinueAuthentication)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn reason_code(mut self, rc: AuthReasonCode) -> Self {
        self.reason_code_buf = Some(Some([rc as u8]));
        // For AUTH packets, if reason_code is set and props is not already set, set empty props
        if self.props.is_none() {
            self.props = Some(Some(Properties::new()));
        }
        self
    }

    /// Build the AUTH packet from the current configuration
    ///
    /// Validates the current builder state and constructs the final AUTH packet.
    /// This method performs comprehensive validation to ensure the packet complies
    /// with MQTT v5.0 protocol requirements.
    ///
    /// # Returns
    ///
    /// * `Ok(Auth)` - Successfully constructed AUTH packet
    /// * `Err(MqttError::MalformedPacket)` - If the packet structure is invalid
    /// * `Err(MqttError::ProtocolError)` - If the packet violates protocol rules
    ///
    /// # Validation
    ///
    /// The build process validates:
    /// - Properties cannot exist without a reason code
    /// - Authentication property relationships are correct
    /// - No invalid property duplicates exist
    /// - Reason code and property combinations are valid
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    /// use mqtt_protocol_core::mqtt::result_code::AuthReasonCode;
    /// use mqtt_protocol_core::mqtt::packet::Properties;
    /// use mqtt_protocol_core::mqtt::packet::Property;
    ///
    /// let auth = mqtt::packet::v5_0::Auth::builder()
    ///     .reason_code(AuthReasonCode::ContinueAuthentication)
    ///     .props(Properties::from_vec(vec![
    ///         Property::AuthenticationMethod("SCRAM-SHA-256".into()),
    ///         Property::AuthenticationData(b"challenge".to_vec()),
    ///     ]))
    ///     .build()?;
    /// ```
    pub fn build(self) -> Result<Auth, 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(Auth {
            fixed_header: [FixedHeader::Auth.as_u8()],
            remaining_length,
            reason_code_buf,
            property_length,
            props,
        })
    }
}

/// Serialize implementation for AUTH packets
///
/// Provides JSON serialization support for AUTH packets, enabling conversion to
/// structured data formats for logging, debugging, and inter-process communication.
///
/// The serialized format includes:
/// - `type`: Always "AUTH" for packet type identification
/// - `reason_code`: The authentication reason code (if present)
/// - `props`: The MQTT v5.0 properties (if present)
///
/// # Examples
///
/// ```ignore
/// use mqtt_protocol_core::mqtt;
/// use mqtt_protocol_core::mqtt::result_code::AuthReasonCode;
/// use serde_json;
///
/// let auth = mqtt::packet::v5_0::Auth::builder()
///     .reason_code(AuthReasonCode::Success)
///     .build()
///     .unwrap();
///
/// let json = serde_json::to_string(&auth).unwrap();
/// // Results in: {"type":"AUTH","reason_code":"Success","props":{}}
/// ```
impl Serialize for Auth {
    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("auth", field_count)?;
        state.serialize_field("type", PacketType::Auth.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()
    }
}

/// Display implementation for AUTH packets
///
/// Provides human-readable string representation of AUTH packets using JSON format.
/// This implementation leverages the `Serialize` trait to create consistent,
/// structured output suitable for logging and debugging.
///
/// If serialization fails, an error message is returned instead of panicking.
///
/// # Examples
///
/// ```ignore
/// use mqtt_protocol_core::mqtt;
/// use mqtt_protocol_core::mqtt::result_code::AuthReasonCode;
///
/// let auth = mqtt::packet::v5_0::Auth::builder()
///     .reason_code(AuthReasonCode::ContinueAuthentication)
///     .build()
///     .unwrap();
///
/// println!("{}", auth);
/// // Outputs: {"type":"AUTH","reason_code":"ContinueAuthentication","props":{}}
/// ```
impl fmt::Display for Auth {
    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}\"}}"),
        }
    }
}

/// Debug implementation for AUTH packets
///
/// Provides debug output for AUTH packets by delegating to the `Display` implementation.
/// This ensures consistent formatting between debug and display representations,
/// which is useful for logging and debugging scenarios.
///
/// The debug output is identical to the display output, showing the packet
/// in JSON format with all relevant fields.
///
/// # Examples
///
/// ```ignore
/// use mqtt_protocol_core::mqtt;
/// use mqtt_protocol_core::mqtt::result_code::AuthReasonCode;
///
/// let auth = mqtt::packet::v5_0::Auth::builder()
///     .reason_code(AuthReasonCode::Success)
///     .build()
///     .unwrap();
///
/// println!("{:?}", auth);
/// // Outputs: {"type":"AUTH","reason_code":"Success","props":{}}
/// ```
impl fmt::Debug for Auth {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

/// GenericPacketTrait implementation for AUTH packets
///
/// Implements the common packet interface that allows AUTH packets to be used
/// polymorphically with other MQTT packet types. This trait provides standardized
/// methods for packet size calculation and buffer generation.
impl GenericPacketTrait for Auth {
    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()
    }
}

/// GenericPacketDisplay implementation for AUTH packets
///
/// Implements the generic packet display interface that provides standardized
/// formatting capabilities for AUTH packets. This trait enables consistent
/// display and debug output across different packet types.
impl GenericPacketDisplay for Auth {
    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)
    }
}

/// Validate AUTH packet properties and reason code combinations
///
/// Performs comprehensive validation of AUTH packet contents to ensure compliance
/// with MQTT v5.0 protocol specifications. This function validates both the
/// individual properties and their relationships with the reason code.
///
/// # Parameters
///
/// * `reason_code` - Optional authentication reason code
/// * `props` - Optional properties to validate
///
/// # Returns
///
/// * `Ok(())` - If the packet configuration is valid
/// * `Err(MqttError::ProtocolError)` - If the packet violates MQTT protocol rules
///
/// # Validation Rules
///
/// ## Property Validation
/// - Authentication Method: Maximum one occurrence allowed
/// - Authentication Data: Maximum one occurrence allowed
/// - Reason String: Maximum one occurrence allowed
/// - User Property: Multiple occurrences allowed
/// - No other properties are permitted in AUTH packets
///
/// ## Property Relationships
/// - Authentication Data requires Authentication Method to be present
/// - If reason code is not Success, Authentication Method is required
/// - If no properties are present, reason code must be Success (or absent)
///
/// ## Protocol Compliance
/// - Ensures proper authentication flow state management
/// - Validates required property combinations for extended authentication
/// - Prevents invalid property combinations that could cause protocol errors
///
/// # Examples
///
/// ```ignore
/// use mqtt_protocol_core::mqtt;
/// use mqtt_protocol_core::mqtt::result_code::AuthReasonCode;
/// use mqtt_protocol_core::mqtt::packet::Properties;
/// use mqtt_protocol_core::mqtt::packet::Property;
///
/// // Valid: Success with no special properties required
/// validate_auth_packet(Some(AuthReasonCode::Success), &None)?;
///
/// // Valid: Continue authentication with method
/// let props = Properties::from_vec(vec![
///     Property::AuthenticationMethod("SCRAM-SHA-256".into())
/// ]);
/// validate_auth_packet(Some(AuthReasonCode::ContinueAuthentication), &Some(props))?;
///
/// // Invalid: Continue authentication without method
/// validate_auth_packet(Some(AuthReasonCode::ContinueAuthentication), &None); // Error
/// ```
fn validate_auth_packet(
    reason_code: Option<AuthReasonCode>,
    props: &Option<Properties>,
) -> Result<(), MqttError> {
    // Validate properties if present
    if let Some(properties) = props {
        let mut count_authentication_method = 0;
        let mut count_authentication_data = 0;
        let mut count_reason_string = 0;

        for prop in properties {
            match prop {
                Property::AuthenticationMethod(_) => count_authentication_method += 1,
                Property::AuthenticationData(_) => count_authentication_data += 1,
                Property::ReasonString(_) => count_reason_string += 1,
                Property::UserProperty(_) => {}
                _ => return Err(MqttError::ProtocolError),
            }
        }

        // Check for duplicates
        if count_authentication_method > 1 {
            return Err(MqttError::ProtocolError);
        }
        if count_authentication_data > 1 {
            return Err(MqttError::ProtocolError);
        }
        if count_reason_string > 1 {
            return Err(MqttError::ProtocolError);
        }

        // AuthenticationData requires AuthenticationMethod
        if count_authentication_data > 0 && count_authentication_method == 0 {
            return Err(MqttError::ProtocolError);
        }

        // If reason code is not Success, Authentication Method is required
        if let Some(rc) = reason_code {
            if rc != AuthReasonCode::Success && count_authentication_method == 0 {
                return Err(MqttError::ProtocolError);
            }
        }
    } else {
        // No properties case
        if let Some(rc) = reason_code {
            if rc != AuthReasonCode::Success {
                // Non-Success reason code without properties is invalid
                return Err(MqttError::ProtocolError);
            }
        }
    }

    Ok(())
}