GenericUnsubscribe

Struct GenericUnsubscribe 

Source
pub struct GenericUnsubscribe<PacketIdType>
where PacketIdType: IsPacketId,
{ pub props: Properties, /* private fields */ }
Expand description

MQTT 5.0 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 5.0 specification, 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 and properties
  • 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
  • Properties: MQTT 5.0 properties that can modify the behavior of the unsubscription

§Payload

The payload contains one or more topic filter strings to unsubscribe from. Each topic filter is a UTF-8 encoded string that matches the exact 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.

§Properties

MQTT 5.0 UNSUBSCRIBE packets can include:

  • User Properties: Custom key-value pairs for application-specific data

Other properties are not allowed in UNSUBSCRIBE packets and will result in a protocol error.

§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

use mqtt_protocol_core::mqtt;

// Create a simple UNSUBSCRIBE packet for a single topic
let unsubscribe = mqtt::packet::v5_0::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::v5_0::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();

Fields§

§props: Properties

MQTT 5.0 properties for the UNSUBSCRIBE packet

Contains the properties that modify the behavior of the unsubscription. For UNSUBSCRIBE packets, only User Properties are allowed.

Implementations§

Source§

impl<PacketIdType> GenericUnsubscribe<PacketIdType>
where PacketIdType: IsPacketId,

Source

pub fn props(&self) -> &Properties

MQTT 5.0 properties for the UNSUBSCRIBE packet

Contains the properties that modify the behavior of the unsubscription. For UNSUBSCRIBE packets, only User Properties are allowed.

Source§

impl<PacketIdType> GenericUnsubscribe<PacketIdType>
where PacketIdType: IsPacketId,

Source

pub fn builder() -> GenericUnsubscribeBuilder<PacketIdType>

Creates a new builder for constructing an UNSUBSCRIBE packet

The builder pattern allows for flexible construction of UNSUBSCRIBE packets with various combinations of properties and topic filters. All UNSUBSCRIBE packets must have a packet identifier and at least one topic filter.

§Returns

A GenericUnsubscribeBuilder instance with default values

§Examples
use mqtt_protocol_core::mqtt;

let unsubscribe = mqtt::packet::v5_0::Unsubscribe::builder()
    .packet_id(42)
    .entries(vec!["sensors/+", "alerts/#"])
    .unwrap()
    .build()
    .unwrap();
Source

pub fn packet_type() -> PacketType

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
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::packet_type::PacketType;

assert_eq!(mqtt::packet::v5_0::Unsubscribe::packet_type(), PacketType::Unsubscribe);
Source

pub fn packet_id(&self) -> PacketIdType

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
use mqtt_protocol_core::mqtt;

let unsubscribe = mqtt::packet::v5_0::Unsubscribe::builder()
    .packet_id(123)
    .entries(vec!["test/topic"])
    .unwrap()
    .build()
    .unwrap();

assert_eq!(unsubscribe.packet_id(), 123);
Source

pub fn entries(&self) -> &Vec<MqttString>

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
use mqtt_protocol_core::mqtt;

let unsubscribe = mqtt::packet::v5_0::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/+");
Source

pub fn parse(data: &[u8]) -> Result<(Self, usize), MqttError>

Parses an UNSUBSCRIBE packet from raw bytes

Deserializes an UNSUBSCRIBE packet from its binary representation according to the MQTT 5.0 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)
  • Invalid properties are present
  • UTF-8 decoding fails for topic filters
§Examples
use mqtt_protocol_core::mqtt;

// Assuming you have raw packet data
let packet_data = &[/* packet bytes */];

match mqtt::packet::v5_0::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);
    }
}
Source

pub fn size(&self) -> usize

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
use mqtt_protocol_core::mqtt;

let unsubscribe = mqtt::packet::v5_0::Unsubscribe::builder()
    .packet_id(1)
    .entries(vec!["test/topic"])
    .unwrap()
    .build()
    .unwrap();

let size = unsubscribe.size();
println!("UNSUBSCRIBE packet size: {} bytes", size);
Source

pub fn to_buffers(&self) -> Vec<IoSlice<'_>>

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 UNSUBSCRIBE packet in wire format.

§Returns

A vector of IoSlice objects for vectored I/O operations

§Examples
use mqtt_protocol_core::mqtt;

let unsubscribe = mqtt::packet::v5_0::Unsubscribe::builder()
    .packet_id(1u16)
    .entries(vec!["test/topic"])
    .unwrap()
    .build()
    .unwrap();

let buffers = unsubscribe.to_buffers();
// Use with vectored write: socket.write_vectored(&buffers)?;
Source

pub fn to_continuous_buffer(&self) -> Vec<u8>

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 UNSUBSCRIBE packet serialized according to the MQTT v5.0 protocol specification, including fixed header, remaining length, packet identifier, properties, and topic filter entries.

§Returns

A vector containing the complete packet data

§Examples
use mqtt_protocol_core::mqtt;

let unsubscribe = mqtt::packet::v5_0::Unsubscribe::builder()
    .packet_id(1u16)
    .entries(vec!["test/topic"])
    .unwrap()
    .build()
    .unwrap();

let buffer = unsubscribe.to_continuous_buffer();
// buffer contains all packet bytes

Trait Implementations§

Source§

impl<PacketIdType> Clone for GenericUnsubscribe<PacketIdType>
where PacketIdType: IsPacketId + Clone, PacketIdType::Buffer: Clone,

Source§

fn clone(&self) -> GenericUnsubscribe<PacketIdType>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<PacketIdType> Debug for GenericUnsubscribe<PacketIdType>
where PacketIdType: IsPacketId + Serialize,

Debug implementation for UNSUBSCRIBE packets

Provides the same output as the Display implementation for consistent formatting across different contexts.

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<PacketIdType> Display for GenericUnsubscribe<PacketIdType>
where PacketIdType: IsPacketId + Serialize,

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

use mqtt_protocol_core::mqtt;

let unsubscribe = mqtt::packet::v5_0::Unsubscribe::builder()
    .packet_id(42)
    .entries(vec!["home/temperature"])
    .unwrap()
    .build()
    .unwrap();

println!("UNSUBSCRIBE packet: {}", unsubscribe);
Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<PacketIdType> From<GenericUnsubscribe<PacketIdType>> for GenericPacket<PacketIdType>
where PacketIdType: IsPacketId + Serialize,

Source§

fn from(v: GenericUnsubscribe<PacketIdType>) -> GenericPacket<PacketIdType>

Converts to this type from the input type.
Source§

impl<PacketIdType> GenericPacketDisplay for GenericUnsubscribe<PacketIdType>
where PacketIdType: IsPacketId + Serialize,

Generic packet display trait implementation for UNSUBSCRIBE packets

Provides display formatting methods for consistent packet output across the MQTT protocol framework.

Source§

fn fmt_debug(&self, f: &mut Formatter<'_>) -> Result

Source§

fn fmt_display(&self, f: &mut Formatter<'_>) -> Result

Source§

impl<PacketIdType> GenericPacketTrait for GenericUnsubscribe<PacketIdType>
where PacketIdType: IsPacketId,

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.

Source§

fn size(&self) -> usize

Source§

fn to_buffers(&self) -> Vec<IoSlice<'_>>

Source§

fn to_continuous_buffer(&self) -> Vec<u8>

Create a continuous buffer containing the complete packet data Read more
Source§

impl<PacketIdType> PacketKind for GenericUnsubscribe<PacketIdType>
where PacketIdType: IsPacketId,

Source§

const IS_UNSUBSCRIBE: bool = true

true if this is an UNSUBSCRIBE packet
Source§

const IS_V5_0: bool = true

true if this is an MQTT v5.0 packet
Source§

const IS_CONNECT: bool = false

true if this is a CONNECT packet
Source§

const IS_CONNACK: bool = false

true if this is a CONNACK packet
Source§

const IS_PUBLISH: bool = false

true if this is a PUBLISH packet
Source§

const IS_PUBACK: bool = false

true if this is a PUBACK packet
Source§

const IS_PUBREC: bool = false

true if this is a PUBREC packet
Source§

const IS_PUBREL: bool = false

true if this is a PUBREL packet
Source§

const IS_PUBCOMP: bool = false

true if this is a PUBCOMP packet
Source§

const IS_SUBSCRIBE: bool = false

true if this is a SUBSCRIBE packet
Source§

const IS_SUBACK: bool = false

true if this is a SUBACK packet
Source§

const IS_UNSUBACK: bool = false

true if this is an UNSUBACK packet
Source§

const IS_PINGREQ: bool = false

true if this is a PINGREQ packet
Source§

const IS_PINGRESP: bool = false

true if this is a PINGRESP packet
Source§

const IS_DISCONNECT: bool = false

true if this is a DISCONNECT packet
Source§

const IS_AUTH: bool = false

true if this is an AUTH packet (v5.0 only)
Source§

const IS_V3_1_1: bool = false

true if this is an MQTT v3.1.1 packet
Source§

impl<PacketIdType> PartialEq for GenericUnsubscribe<PacketIdType>
where PacketIdType: IsPacketId + PartialEq, PacketIdType::Buffer: PartialEq,

Source§

fn eq(&self, other: &GenericUnsubscribe<PacketIdType>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<PacketIdType> Serialize for GenericUnsubscribe<PacketIdType>
where PacketIdType: IsPacketId + Serialize,

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, properties (if any), 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
  • props: Properties object (only included if not empty)
  • entries: Array of topic filter strings (only included if not empty)
Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<PacketIdType> TryInto<GenericUnsubscribe<PacketIdType>> for GenericPacket<PacketIdType>
where PacketIdType: IsPacketId + Serialize,

Source§

type Error = &'static str

The type returned in the event of a conversion error.
Source§

fn try_into( self, ) -> Result<GenericUnsubscribe<PacketIdType>, <Self as TryInto<GenericUnsubscribe<PacketIdType>>>::Error>

Performs the conversion.
Source§

impl<PacketIdType> Eq for GenericUnsubscribe<PacketIdType>
where PacketIdType: IsPacketId + Eq, PacketIdType::Buffer: Eq,

Source§

impl<PacketIdType> SendableRole<Any> for GenericUnsubscribe<PacketIdType>
where PacketIdType: IsPacketId,

Source§

impl<PacketIdType> SendableRole<Client> for GenericUnsubscribe<PacketIdType>
where PacketIdType: IsPacketId,

Source§

impl<PacketIdType> StructuralPartialEq for GenericUnsubscribe<PacketIdType>
where PacketIdType: IsPacketId,

Auto Trait Implementations§

§

impl<PacketIdType> Freeze for GenericUnsubscribe<PacketIdType>
where <PacketIdType as IsPacketId>::Buffer: Freeze,

§

impl<PacketIdType> RefUnwindSafe for GenericUnsubscribe<PacketIdType>
where <PacketIdType as IsPacketId>::Buffer: RefUnwindSafe,

§

impl<PacketIdType> Send for GenericUnsubscribe<PacketIdType>
where <PacketIdType as IsPacketId>::Buffer: Send,

§

impl<PacketIdType> Sync for GenericUnsubscribe<PacketIdType>
where <PacketIdType as IsPacketId>::Buffer: Sync,

§

impl<PacketIdType> Unpin for GenericUnsubscribe<PacketIdType>
where <PacketIdType as IsPacketId>::Buffer: Unpin,

§

impl<PacketIdType> UnwindSafe for GenericUnsubscribe<PacketIdType>
where <PacketIdType as IsPacketId>::Buffer: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<Role, PacketIdType, T> Sendable<Role, PacketIdType> for T
where Role: RoleType, PacketIdType: IsPacketId, T: SendableRole<Role> + SendableVersion + Display + Debug + PacketKind + SendableHelper<Role, PacketIdType>,

Source§

fn dispatch_send( self, connection: &mut GenericConnection<Role, PacketIdType>, ) -> Vec<GenericEvent<PacketIdType>>

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.