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
// 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 core::mem;
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::mqtt_string::MqttString;
use crate::mqtt::packet::packet_type::{FixedHeader, PacketType};
use crate::mqtt::packet::variable_byte_integer::VariableByteInteger;
use crate::mqtt::packet::GenericPacketDisplay;
use crate::mqtt::packet::GenericPacketTrait;
use crate::mqtt::packet::IsPacketId;
use crate::mqtt::result_code::MqttError;

/// MQTT 3.1.1 UNSUBSCRIBE packet representation
///
/// The UNSUBSCRIBE packet is sent by a client to unsubscribe from one or more topic filters
/// on the server. This removes existing subscriptions and stops the flow of messages
/// from the server to the client for the specified topic filters.
///
/// According to MQTT 3.1.1 specification section 3.10, the UNSUBSCRIBE packet contains:
/// - Fixed header with packet type (bit 7-4 = 1010), reserved flags (bit 3-0 = 0010), and remaining length
/// - Variable header with packet identifier
/// - Payload containing one or more topic filter strings to unsubscribe from
///
/// # Fixed Header
///
/// The UNSUBSCRIBE packet uses a fixed header with:
/// - **Packet Type**: 10 (1010 binary) in bits 7-4 of the first byte
/// - **Reserved Flags**: 2 (0010 binary) in bits 3-0 - these flags are reserved and must be set as shown
/// - **Remaining Length**: Variable length encoding of the remaining packet data
///
/// # Variable Header
///
/// The variable header contains:
/// - **Packet Identifier**: A 16-bit identifier used to match UNSUBSCRIBE with UNSUBACK packets
///
/// # Payload
///
/// The payload contains one or more topic filter strings to unsubscribe from.
/// Each topic filter is a UTF-8 encoded string that must exactly match the topic filter
/// used in the original SUBSCRIBE packet. Wildcards are allowed and work the same
/// as in SUBSCRIBE packets.
///
/// # Topic Filters and Wildcards
///
/// Topic filters in UNSUBSCRIBE packets can include the same wildcards as SUBSCRIBE:
/// - **Single-level wildcard (+)**: Matches exactly one topic level (e.g., "sport/+/player1")
/// - **Multi-level wildcard (#)**: Matches any number of topic levels (e.g., "sport/#")
///
/// The topic filter must exactly match the topic filter used in the original subscription.
///
/// # Protocol Differences from MQTT 5.0
///
/// MQTT 3.1.1 UNSUBSCRIBE packets differ from MQTT 5.0 in several ways:
/// - No properties section in the variable header
/// - No user properties or other MQTT 5.0 properties
/// - Simpler packet structure with fewer configuration options
/// - Direct topic filter list without additional subscription options
///
/// # Generic Type Parameter
///
/// The `PacketIdType` generic parameter allows using packet identifiers larger than
/// the standard u16, which can be useful for broker clusters to avoid packet ID
/// exhaustion when extending the MQTT protocol.
///
/// # Examples
///
/// ```ignore
/// use mqtt_protocol_core::mqtt;
///
/// // Create a simple UNSUBSCRIBE packet for a single topic
/// let unsubscribe = mqtt::packet::v3_1_1::Unsubscribe::builder()
///     .packet_id(42)
///     .entries(vec!["sensors/temperature"])
///     .unwrap()
///     .build()
///     .unwrap();
///
/// assert_eq!(unsubscribe.packet_id(), 42);
/// assert_eq!(unsubscribe.entries().len(), 1);
/// assert_eq!(unsubscribe.entries()[0].as_str(), "sensors/temperature");
///
/// // Create an UNSUBSCRIBE packet with multiple topics
/// let unsubscribe = mqtt::packet::v3_1_1::Unsubscribe::builder()
///     .packet_id(123)
///     .entries(vec![
///         "home/+/temperature",
///         "alerts/#",
///         "sensors/humidity"
///     ])
///     .unwrap()
///     .build()
///     .unwrap();
///
/// assert_eq!(unsubscribe.packet_id(), 123);
/// assert_eq!(unsubscribe.entries().len(), 3);
///
/// // Serialize to bytes for network transmission
/// let buffers = unsubscribe.to_buffers();
/// let total_size = unsubscribe.size();
/// ```
#[derive(PartialEq, Eq, Builder, Clone, Getters, CopyGetters)]
#[builder(no_std, derive(Debug), pattern = "owned", setter(into), build_fn(skip))]
pub struct GenericUnsubscribe<PacketIdType>
where
    PacketIdType: IsPacketId,
{
    #[builder(private)]
    fixed_header: [u8; 1],
    #[builder(private)]
    remaining_length: VariableByteInteger,
    #[builder(private)]
    packet_id_buf: PacketIdType::Buffer,

    /// Topic filter entries to unsubscribe from
    ///
    /// Contains the list of topic filter strings that the client wants to
    /// unsubscribe from. Each entry must exactly match a topic filter from
    /// a previous SUBSCRIBE packet.
    #[builder(default = "Vec::new()", setter(custom))]
    entry_bufs: Vec<MqttString>,
}

/// Type alias for UNSUBSCRIBE packet with standard u16 packet identifiers
///
/// This is the most commonly used UNSUBSCRIBE packet type for standard MQTT 3.1.1
/// implementations that use 16-bit packet identifiers as specified in the protocol.
///
/// # Examples
///
/// ```ignore
/// use mqtt_protocol_core::mqtt;
///
/// let unsubscribe = mqtt::packet::v3_1_1::Unsubscribe::builder()
///     .packet_id(1)
///     .entries(vec!["my/topic", "another/topic"])
///     .unwrap()
///     .build()
///     .unwrap();
/// ```
pub type Unsubscribe = GenericUnsubscribe<u16>;

impl<PacketIdType> GenericUnsubscribe<PacketIdType>
where
    PacketIdType: IsPacketId,
{
    /// Creates a new builder for constructing an UNSUBSCRIBE packet
    ///
    /// The builder pattern allows for flexible construction of UNSUBSCRIBE packets
    /// with various combinations of topic filters. All UNSUBSCRIBE packets must have
    /// a packet identifier and at least one topic filter.
    ///
    /// # Returns
    ///
    /// A `GenericUnsubscribeBuilder` instance with default values
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    ///
    /// let unsubscribe = mqtt::packet::v3_1_1::Unsubscribe::builder()
    ///     .packet_id(42)
    ///     .entries(vec!["sensors/+", "alerts/#"])
    ///     .unwrap()
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn builder() -> GenericUnsubscribeBuilder<PacketIdType> {
        GenericUnsubscribeBuilder::<PacketIdType>::default()
    }

    /// Returns the packet type for UNSUBSCRIBE packets
    ///
    /// This is always `PacketType::Unsubscribe` for UNSUBSCRIBE packet instances.
    /// The numeric value is 10, represented as 1010 in the upper 4 bits of the
    /// fixed header's first byte.
    ///
    /// # Returns
    ///
    /// `PacketType::Unsubscribe`
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    /// use mqtt_protocol_core::mqtt::packet::packet_type::PacketType;
    ///
    /// assert_eq!(mqtt::packet::v3_1_1::Unsubscribe::packet_type(), PacketType::Unsubscribe);
    /// ```
    pub fn packet_type() -> PacketType {
        PacketType::Unsubscribe
    }

    /// Returns the packet identifier for this UNSUBSCRIBE packet
    ///
    /// The packet identifier is used to match UNSUBSCRIBE packets with their corresponding
    /// UNSUBACK responses. It must be non-zero as specified in the MQTT protocol.
    /// The same packet identifier should not be reused until the UNSUBACK is received.
    ///
    /// # Returns
    ///
    /// The packet identifier as `PacketIdType`
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    ///
    /// let unsubscribe = mqtt::packet::v3_1_1::Unsubscribe::builder()
    ///     .packet_id(123)
    ///     .entries(vec!["test/topic"])
    ///     .unwrap()
    ///     .build()
    ///     .unwrap();
    ///
    /// assert_eq!(unsubscribe.packet_id(), 123);
    /// ```
    pub fn packet_id(&self) -> PacketIdType {
        PacketIdType::from_buffer(self.packet_id_buf.as_ref())
    }

    /// Returns the topic filter entries to unsubscribe from
    ///
    /// Returns a reference to the vector of topic filter strings that this
    /// UNSUBSCRIBE packet requests to unsubscribe from. Each topic filter
    /// must exactly match a topic filter from a previous SUBSCRIBE packet.
    ///
    /// # Returns
    ///
    /// A reference to the vector of `MqttString` topic filters
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    ///
    /// let unsubscribe = mqtt::packet::v3_1_1::Unsubscribe::builder()
    ///     .packet_id(1)
    ///     .entries(vec!["home/temperature", "sensors/+"])
    ///     .unwrap()
    ///     .build()
    ///     .unwrap();
    ///
    /// let entries = unsubscribe.entries();
    /// assert_eq!(entries.len(), 2);
    /// assert_eq!(entries[0].as_str(), "home/temperature");
    /// assert_eq!(entries[1].as_str(), "sensors/+");
    /// ```
    pub fn entries(&self) -> &Vec<MqttString> {
        &self.entry_bufs
    }

    /// Parses an UNSUBSCRIBE packet from raw bytes
    ///
    /// Deserializes an UNSUBSCRIBE packet from its binary representation according
    /// to the MQTT 3.1.1 specification. The input should contain the variable header
    /// and payload data (excluding the fixed header).
    ///
    /// # Parameters
    ///
    /// * `data` - Byte slice containing the packet data (variable header + payload)
    ///
    /// # Returns
    ///
    /// Returns a tuple containing:
    /// - The parsed `GenericUnsubscribe` packet
    /// - The number of bytes consumed during parsing
    ///
    /// # Errors
    ///
    /// Returns `MqttError` if:
    /// - The packet is malformed or incomplete
    /// - The packet identifier is zero (invalid)
    /// - No topic filter entries are present (protocol error)
    /// - UTF-8 decoding fails for topic filters
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    ///
    /// // Assuming you have raw packet data
    /// let packet_data = &[/* packet bytes */];
    ///
    /// match mqtt::packet::v3_1_1::Unsubscribe::parse(packet_data) {
    ///     Ok((unsubscribe, bytes_consumed)) => {
    ///         println!("Parsed UNSUBSCRIBE with packet ID: {}", unsubscribe.packet_id());
    ///         println!("Consumed {} bytes", bytes_consumed);
    ///     }
    ///     Err(e) => {
    ///         eprintln!("Failed to parse UNSUBSCRIBE packet: {:?}", e);
    ///     }
    /// }
    /// ```
    pub fn parse(data: &[u8]) -> Result<(Self, usize), MqttError> {
        let mut cursor = 0;
        let buffer_size = mem::size_of::<<PacketIdType as IsPacketId>::Buffer>();

        if data.len() < buffer_size {
            return Err(MqttError::MalformedPacket);
        }

        let packet_id = PacketIdType::from_buffer(&data[0..buffer_size]);
        let packet_id_buf = packet_id.to_buffer();
        cursor += buffer_size;

        let mut entries = Vec::new();
        while cursor < data.len() {
            let (mqtt_string, consumed) = MqttString::decode(&data[cursor..])?;
            entries.push(mqtt_string);
            cursor += consumed;
        }

        if entries.is_empty() {
            return Err(MqttError::ProtocolError);
        }

        let remaining_size = buffer_size + entries.iter().map(|e| e.size()).sum::<usize>();
        let remaining_length = VariableByteInteger::from_u32(remaining_size as u32).unwrap();

        let unsubscribe = GenericUnsubscribe {
            fixed_header: [FixedHeader::Unsubscribe as u8],
            remaining_length,
            packet_id_buf,
            entry_bufs: entries,
        };

        Ok((unsubscribe, cursor))
    }

    /// Returns the total size of the UNSUBSCRIBE packet in bytes
    ///
    /// Calculates the total size including the fixed header, variable header,
    /// and payload. This is useful for buffer allocation and network transmission.
    ///
    /// # Returns
    ///
    /// The total packet size in bytes
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    ///
    /// let unsubscribe = mqtt::packet::v3_1_1::Unsubscribe::builder()
    ///     .packet_id(1)
    ///     .entries(vec!["test/topic"])
    ///     .unwrap()
    ///     .build()
    ///     .unwrap();
    ///
    /// let size = unsubscribe.size();
    /// println!("UNSUBSCRIBE packet size: {} bytes", size);
    /// ```
    pub fn size(&self) -> usize {
        1 + self.remaining_length.size() + self.remaining_length.to_u32() as usize
    }

    /// Converts the UNSUBSCRIBE packet to a vector of I/O slices for efficient network transmission
    ///
    /// Creates a vector of `IoSlice` references that can be used with vectored I/O operations
    /// for efficient transmission without copying data. The slices represent the complete
    /// MQTT packet in wire format.
    ///
    /// # Returns
    ///
    /// A vector of `IoSlice` containing references to the packet data
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    /// use std::io::IoSlice;
    ///
    /// let unsubscribe = mqtt::packet::v3_1_1::Unsubscribe::builder()
    ///     .packet_id(1)
    ///     .entries(vec!["test/topic"])
    ///     .unwrap()
    ///     .build()
    ///     .unwrap();
    ///
    /// let buffers: Vec<IoSlice> = unsubscribe.to_buffers();
    /// // Use buffers for vectored I/O operations
    /// ```
    #[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()));
        bufs.push(IoSlice::new(self.packet_id_buf.as_ref()));

        for entry in &self.entry_bufs {
            bufs.extend(entry.to_buffers());
        }

        bufs
    }

    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());
        buf.extend_from_slice(self.packet_id_buf.as_ref());

        for entry in &self.entry_bufs {
            buf.append(&mut entry.to_continuous_buffer());
        }

        buf
    }
}

/// Builder implementation for UNSUBSCRIBE packets
///
/// Provides methods for constructing UNSUBSCRIBE packets with validation.
/// The builder ensures that all required fields are set and validates the
/// packet according to MQTT 3.1.1 specifications before building.
impl<PacketIdType> GenericUnsubscribeBuilder<PacketIdType>
where
    PacketIdType: IsPacketId,
{
    /// Sets the packet identifier for the UNSUBSCRIBE packet
    ///
    /// The packet identifier must be non-zero and is used to match the UNSUBSCRIBE
    /// packet with its corresponding UNSUBACK response.
    ///
    /// # Parameters
    ///
    /// * `id` - The packet identifier (must be non-zero)
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    ///
    /// let builder = mqtt::packet::v3_1_1::Unsubscribe::builder()
    ///     .packet_id(42);
    /// ```
    pub fn packet_id(mut self, id: PacketIdType) -> Self {
        self.packet_id_buf = Some(id.to_buffer());
        self
    }

    /// Sets the topic filter entries to unsubscribe from
    ///
    /// Accepts any iterable of items that can be converted to MQTT strings.
    /// Each topic filter must be a valid UTF-8 string and can contain wildcards.
    /// The topic filters should exactly match those used in previous SUBSCRIBE packets.
    ///
    /// # Parameters
    ///
    /// * `entries` - An iterable of topic filter strings
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining, or an error if conversion fails
    ///
    /// # Errors
    ///
    /// Returns `MqttError` if:
    /// - Any topic filter contains invalid UTF-8
    /// - Topic filter length exceeds MQTT limits
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    ///
    /// // Single topic filter
    /// let builder = mqtt::packet::v3_1_1::Unsubscribe::builder()
    ///     .entries(vec!["home/temperature"])
    ///     .unwrap();
    ///
    /// // Multiple topic filters with wildcards
    /// let builder = mqtt::packet::v3_1_1::Unsubscribe::builder()
    ///     .entries(vec!["sensors/+", "alerts/#", "home/kitchen/temperature"])
    ///     .unwrap();
    /// ```
    pub fn entries<I, T>(mut self, entries: I) -> Result<Self, MqttError>
    where
        I: IntoIterator<Item = T>,
        T: TryInto<MqttString>,
        T::Error: Into<MqttError>,
    {
        let mqtt_strings: Result<Vec<_>, _> = entries
            .into_iter()
            .map(|item| item.try_into().map_err(Into::into))
            .collect();

        self.entry_bufs = Some(mqtt_strings?);
        Ok(self)
    }

    /// Validates the builder state before constructing the packet
    ///
    /// Ensures that all required fields are set and validates the packet
    /// according to MQTT 3.1.1 specifications.
    ///
    /// # Returns
    ///
    /// `Ok(())` if validation passes, otherwise `MqttError`
    ///
    /// # Errors
    ///
    /// Returns `MqttError::MalformedPacket` if:
    /// - Packet identifier is not set or is zero
    ///
    /// Returns `MqttError::ProtocolError` if:
    /// - No topic filter entries are provided
    fn validate(&self) -> Result<(), MqttError> {
        if self.packet_id_buf.is_none() {
            return Err(MqttError::MalformedPacket);
        }

        let packet_id_bytes = self.packet_id_buf.as_ref().unwrap().as_ref();
        let all_zeros = packet_id_bytes.iter().all(|&b| b == 0);
        if all_zeros {
            return Err(MqttError::MalformedPacket);
        }

        if self.entry_bufs.as_ref().map_or(true, |e| e.is_empty()) {
            return Err(MqttError::ProtocolError);
        }

        Ok(())
    }

    /// Builds the UNSUBSCRIBE packet after validation
    ///
    /// Constructs the final UNSUBSCRIBE packet with all specified fields.
    /// Performs validation to ensure the packet conforms to MQTT 3.1.1 specifications.
    ///
    /// # Returns
    ///
    /// The constructed `GenericUnsubscribe` packet
    ///
    /// # Errors
    ///
    /// Returns `MqttError` if:
    /// - Required fields are missing (packet ID, entries)
    /// - Packet identifier is zero
    /// - No topic filter entries are provided
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use mqtt_protocol_core::mqtt;
    ///
    /// let unsubscribe = mqtt::packet::v3_1_1::Unsubscribe::builder()
    ///     .packet_id(42)
    ///     .entries(vec!["home/temperature", "sensors/humidity"])
    ///     .unwrap()
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn build(self) -> Result<GenericUnsubscribe<PacketIdType>, MqttError> {
        self.validate()?;

        let packet_id_buf = self.packet_id_buf.unwrap();
        let entries = self.entry_bufs.unwrap_or_default();

        let packet_id_size = mem::size_of::<<PacketIdType as IsPacketId>::Buffer>();
        let entries_size = entries.iter().map(|e| e.size()).sum::<usize>();

        let remaining = packet_id_size + entries_size;
        let remaining_length = VariableByteInteger::from_u32(remaining as u32).unwrap();

        Ok(GenericUnsubscribe {
            fixed_header: [FixedHeader::Unsubscribe as u8],
            remaining_length,
            packet_id_buf,
            entry_bufs: entries,
        })
    }
}

/// Serialization implementation for UNSUBSCRIBE packets
///
/// Enables JSON serialization of UNSUBSCRIBE packets for debugging, logging,
/// and API integration purposes. The serialized format includes the packet type,
/// packet identifier, and topic filter entries.
///
/// # Serialized Format
///
/// The packet is serialized as a JSON object with these fields:
/// - `type`: Always "unsubscribe"
/// - `packet_id`: The packet identifier
/// - `entries`: Array of topic filter strings (only included if not empty)
impl<PacketIdType> Serialize for GenericUnsubscribe<PacketIdType>
where
    PacketIdType: IsPacketId + Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut field_count = 2; // type and packet_id are always present

        if !self.entry_bufs.is_empty() {
            field_count += 1;
        }

        let mut state = serializer.serialize_struct("Unsubscribe", field_count)?;

        state.serialize_field("type", "unsubscribe")?;
        state.serialize_field("packet_id", &self.packet_id())?;

        if !self.entry_bufs.is_empty() {
            state.serialize_field("entries", &self.entry_bufs)?;
        }

        state.end()
    }
}

/// Display implementation for UNSUBSCRIBE packets
///
/// Provides a human-readable string representation of the UNSUBSCRIBE packet
/// using JSON formatting. This is useful for debugging and logging purposes.
///
/// # Examples
///
/// ```ignore
/// use mqtt_protocol_core::mqtt;
///
/// let unsubscribe = mqtt::packet::v3_1_1::Unsubscribe::builder()
///     .packet_id(42)
///     .entries(vec!["home/temperature"])
///     .unwrap()
///     .build()
///     .unwrap();
///
/// println!("UNSUBSCRIBE packet: {}", unsubscribe);
/// ```
impl<PacketIdType> fmt::Display for GenericUnsubscribe<PacketIdType>
where
    PacketIdType: IsPacketId + Serialize,
{
    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 UNSUBSCRIBE packets
///
/// Provides the same output as the Display implementation for consistent
/// formatting across different contexts.
impl<PacketIdType> fmt::Debug for GenericUnsubscribe<PacketIdType>
where
    PacketIdType: IsPacketId + Serialize,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

/// Generic packet trait implementation for UNSUBSCRIBE packets
///
/// Provides common packet operations required by the MQTT protocol framework.
/// This trait allows UNSUBSCRIBE packets to be used polymorphically with other
/// packet types in the protocol implementation.
impl<PacketIdType> GenericPacketTrait for GenericUnsubscribe<PacketIdType>
where
    PacketIdType: IsPacketId,
{
    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()
    }
}

/// Generic packet display trait implementation for UNSUBSCRIBE packets
///
/// Provides display formatting methods for consistent packet output across
/// the MQTT protocol framework.
impl<PacketIdType> GenericPacketDisplay for GenericUnsubscribe<PacketIdType>
where
    PacketIdType: IsPacketId + Serialize,
{
    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)
    }
}