pub struct GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId,{
pub props: Properties,
/* private fields */
}
Expand description
MQTT 5.0 SUBSCRIBE packet representation
The SUBSCRIBE packet is sent by a client to subscribe to one or more topic filters on the server. Each subscription establishes a flow of messages from the server to the client based on the matching topic filters and their associated subscription options.
According to MQTT 5.0 specification, the SUBSCRIBE packet contains:
- Fixed header with packet type (bit 7-4 = 1000), reserved flags (bit 3-0 = 0010), and remaining length
- Variable header with packet identifier and properties
- Payload containing one or more topic filter entries with subscription options
§Fixed Header
The SUBSCRIBE packet uses a fixed header with:
- Packet Type: 8 (1000 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 SUBSCRIBE with SUBACK packets
- Properties: MQTT 5.0 properties that modify the behavior of the subscription
§Payload
The payload contains one or more subscription entries, each consisting of:
- Topic Filter: UTF-8 encoded string that may contain wildcards (+ and #)
- Subscription Options: Byte containing QoS, No Local, Retain As Published, and Retain Handling flags
§Quality of Service (QoS)
Each subscription specifies a maximum QoS level:
- QoS 0: At most once delivery
- QoS 1: At least once delivery
- QoS 2: Exactly once delivery
§Topic Filters and Wildcards
Topic filters can include wildcards:
- Single-level wildcard (+): Matches exactly one topic level (e.g., “sport/+/player1”)
- Multi-level wildcard (#): Matches any number of topic levels (e.g., “sport/#”)
§MQTT 5.0 Subscription Options
- No Local: If set, messages published by this client are not sent back to it
- Retain As Published: If set, retain flag is preserved when forwarding messages
- Retain Handling: Controls how retained messages are sent when subscription is established
§Properties
MQTT 5.0 SUBSCRIBE packets can include:
- Subscription Identifier: Numeric identifier to associate with the subscription
- User Properties: Custom key-value pairs for application-specific data
§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;
use mqtt_protocol_core::mqtt::packet::qos::Qos;
use mqtt_protocol_core::mqtt::packet::SubEntry;
// Create a simple SUBSCRIBE packet for a single topic
let subscribe = mqtt::packet::v5_0::Subscribe::builder()
.packet_id(42)
.entries(vec![
SubEntry::builder()
.topic_filter("sensors/temperature")
.unwrap()
.qos(Qos::AtLeastOnce)
.build()
.unwrap()
])
.build()
.unwrap();
assert_eq!(subscribe.packet_id(), 42);
assert_eq!(subscribe.entries().len(), 1);
assert_eq!(subscribe.entries()[0].topic_filter(), "sensors/temperature");
// Create a SUBSCRIBE packet with multiple topics and properties
let subscribe = mqtt::packet::v5_0::Subscribe::builder()
.packet_id(123)
.entries(vec![
SubEntry::builder()
.topic_filter("home/+/temperature")
.unwrap()
.qos(Qos::AtMostOnce)
.build()
.unwrap(),
SubEntry::builder()
.topic_filter("alerts/#")
.unwrap()
.qos(Qos::ExactlyOnce)
.no_local(true)
.build()
.unwrap()
])
.build()
.unwrap();
assert_eq!(subscribe.packet_id(), 123);
assert_eq!(subscribe.entries().len(), 2);
// Serialize to bytes for network transmission
let buffers = subscribe.to_buffers();
let total_size = subscribe.size();
Fields§
§props: Properties
Implementations§
Source§impl<PacketIdType> GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId,
impl<PacketIdType> GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId,
Source§impl<PacketIdType> GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId,
impl<PacketIdType> GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId,
Sourcepub fn builder() -> GenericSubscribeBuilder<PacketIdType>
pub fn builder() -> GenericSubscribeBuilder<PacketIdType>
Creates a new builder for constructing a SUBSCRIBE packet
The builder pattern allows for flexible construction of SUBSCRIBE packets with various combinations of properties, topic filters, and subscription options. All SUBSCRIBE packets must have a packet identifier and at least one subscription entry.
§Returns
A GenericSubscribeBuilder
instance with default values
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::qos::Qos;
use mqtt_protocol_core::mqtt::packet::SubEntry;
let subscribe = mqtt::packet::v5_0::Subscribe::builder()
.packet_id(42)
.entries(vec![
SubEntry::builder()
.topic_filter("sensors/+")
.unwrap()
.qos(Qos::AtLeastOnce)
.no_local(true)
.build()
.unwrap()
])
.build()
.unwrap();
Sourcepub fn packet_type() -> PacketType
pub fn packet_type() -> PacketType
Returns the packet type for SUBSCRIBE packets
This is always PacketType::Subscribe
for SUBSCRIBE packet instances.
The numeric value is 8, represented as 1000 in the upper 4 bits of the
fixed header’s first byte.
§Returns
PacketType::Subscribe
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::packet_type::PacketType;
assert_eq!(mqtt::packet::v5_0::Subscribe::packet_type(), PacketType::Subscribe);
Sourcepub fn packet_id(&self) -> PacketIdType
pub fn packet_id(&self) -> PacketIdType
Returns the packet identifier for this SUBSCRIBE packet
The packet identifier is used to match SUBSCRIBE packets with their corresponding SUBACK responses. It must be non-zero as specified in the MQTT protocol. The same packet identifier should not be reused until the SUBACK is received.
§Returns
The packet identifier as PacketIdType
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::qos::Qos;
use mqtt_protocol_core::mqtt::packet::SubEntry;
let subscribe = mqtt::packet::v5_0::Subscribe::builder()
.packet_id(123)
.entries(vec![
SubEntry::builder()
.topic_filter("test/topic")
.unwrap()
.qos(Qos::AtMostOnce)
.build()
.unwrap()
])
.build()
.unwrap();
assert_eq!(subscribe.packet_id(), 123);
Sourcepub fn parse(data: &[u8]) -> Result<(Self, usize), MqttError>
pub fn parse(data: &[u8]) -> Result<(Self, usize), MqttError>
Parses a SUBSCRIBE packet from a byte buffer
This method parses the variable header and payload of a SUBSCRIBE packet, extracting the packet identifier, properties, and subscription entries. The fixed header should be parsed separately before calling this method.
§Arguments
data
- Byte buffer containing the SUBSCRIBE packet data (without fixed header)
§Returns
Ok((GenericSubscribe, usize))
- The parsed SUBSCRIBE packet and number of bytes consumedErr(MqttError)
- If the packet is malformed or contains invalid data
§Errors
MqttError::MalformedPacket
- If the packet structure is invalidMqttError::ProtocolError
- If the packet violates MQTT protocol rules (e.g., no entries)
§Examples
use mqtt_protocol_core::mqtt;
// This would typically be called by a packet parser after reading the fixed header
let data = &[0x00, 0x01, 0x00, 0x00, 0x09, b't', b'e', b's', b't', b'/', b't', b'o', b'p', b'i', b'c', 0x01];
let (subscribe, consumed) = mqtt::packet::v5_0::Subscribe::parse(data).unwrap();
assert_eq!(subscribe.packet_id(), 1);
assert_eq!(consumed, data.len());
Sourcepub fn size(&self) -> usize
pub fn size(&self) -> usize
Returns the total size of the SUBSCRIBE packet in bytes
This includes the fixed header (1 byte for packet type + remaining length encoding) plus all variable header and payload data. This size can be used for buffer allocation before serialization.
§Returns
Total packet size in bytes
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::qos::Qos;
use mqtt_protocol_core::mqtt::packet::SubEntry;
let subscribe = mqtt::packet::v5_0::Subscribe::builder()
.packet_id(1)
.entries(vec![
SubEntry::builder()
.topic_filter("test")
.unwrap()
.qos(Qos::AtMostOnce)
.build()
.unwrap()
])
.build()
.unwrap();
let total_size = subscribe.size();
// Size includes: fixed header + packet_id + properties_length + properties + entries
Sourcepub fn to_buffers(&self) -> Vec<IoSlice<'_>>
pub fn to_buffers(&self) -> Vec<IoSlice<'_>>
Converts the SUBSCRIBE packet to a vector of I/O slices for efficient network transmission
This method serializes the packet into multiple buffer slices without copying data, allowing for efficient vectored I/O operations. The slices are ordered according to the MQTT packet structure.
§Returns
Vector of IoSlice
containing the serialized packet data:
- Fixed header (packet type and flags)
- Remaining length encoding
- Packet identifier
- Properties length encoding
- Properties data (if any)
- Subscription entries (topic filters and options)
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::qos::Qos;
use mqtt_protocol_core::mqtt::packet::SubEntry;
let subscribe = mqtt::packet::v5_0::Subscribe::builder()
.packet_id(1)
.entries(vec![
SubEntry::builder()
.topic_filter("test/topic")
.unwrap()
.qos(Qos::AtLeastOnce)
.build()
.unwrap()
])
.build()
.unwrap();
let buffers = subscribe.to_buffers();
// Use buffers for vectored write operations
Trait Implementations§
Source§impl AsConcrete<GenericSubscribe<u16>> for Packet
impl AsConcrete<GenericSubscribe<u16>> for Packet
fn as_concrete(&self) -> Option<&Subscribe>
Source§impl<PacketIdType> Clone for GenericSubscribe<PacketIdType>
impl<PacketIdType> Clone for GenericSubscribe<PacketIdType>
Source§fn clone(&self) -> GenericSubscribe<PacketIdType>
fn clone(&self) -> GenericSubscribe<PacketIdType>
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read moreSource§impl<PacketIdType> Debug for GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
Debug trait implementation for SUBSCRIBE packets
impl<PacketIdType> Debug for GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
Debug trait implementation for SUBSCRIBE packets
Provides the same output as the Display trait, showing a JSON representation of the packet contents. This is consistent with other packet types in the library.
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::qos::Qos;
use mqtt_protocol_core::mqtt::packet::SubEntry;
let subscribe = mqtt::packet::v5_0::Subscribe::builder()
.packet_id(1)
.entries(vec![
SubEntry::builder()
.topic_filter("debug/topic")
.unwrap()
.qos(Qos::AtMostOnce)
.build()
.unwrap()
])
.build()
.unwrap();
println!("{:?}", subscribe);
Source§impl<PacketIdType> Display for GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
Display trait implementation for SUBSCRIBE packets
impl<PacketIdType> Display for GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
Display trait implementation for SUBSCRIBE packets
Provides a human-readable JSON representation of the SUBSCRIBE packet, including the packet type, packet identifier, properties, and subscription entries. This is useful for debugging and logging purposes.
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::qos::Qos;
use mqtt_protocol_core::mqtt::packet::SubEntry;
let subscribe = mqtt::packet::v5_0::Subscribe::builder()
.packet_id(42)
.entries(vec![
SubEntry::builder()
.topic_filter("test/topic")
.unwrap()
.qos(Qos::AtLeastOnce)
.build()
.unwrap()
])
.build()
.unwrap();
println!("{}", subscribe);
// Output: {"type":"subscribe","packet_id":42,"entries":[...]}
Source§impl<PacketIdType> From<GenericSubscribe<PacketIdType>> for GenericPacket<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
impl<PacketIdType> From<GenericSubscribe<PacketIdType>> for GenericPacket<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
Source§fn from(v: GenericSubscribe<PacketIdType>) -> GenericPacket<PacketIdType>
fn from(v: GenericSubscribe<PacketIdType>) -> GenericPacket<PacketIdType>
Source§impl<PacketIdType> GenericPacketDisplay for GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
Generic packet display trait implementation for SUBSCRIBE packets
impl<PacketIdType> GenericPacketDisplay for GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
Generic packet display trait implementation for SUBSCRIBE packets
Provides unified display formatting for packet types, supporting both debug and display formatting through a common interface. This is used by the packet handling infrastructure for consistent logging and debugging.
Source§impl<PacketIdType> GenericPacketTrait for GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId,
Generic packet trait implementation for SUBSCRIBE packets
impl<PacketIdType> GenericPacketTrait for GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId,
Generic packet trait implementation for SUBSCRIBE packets
Provides the common packet interface used by the MQTT protocol handler. This allows SUBSCRIBE packets to be treated uniformly with other packet types for size calculation and serialization operations.
§Methods
size()
: Returns the total packet size in bytesto_buffers()
: Returns I/O slices for efficient transmission
Source§impl IntoConcreteOwned<GenericSubscribe<u16>> for Packet
impl IntoConcreteOwned<GenericSubscribe<u16>> for Packet
fn into_concrete_owned(self) -> Option<Subscribe>
Source§impl<PacketIdType> PacketKind for GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId,
impl<PacketIdType> PacketKind for GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId,
Source§const IS_SUBSCRIBE: bool = true
const IS_SUBSCRIBE: bool = true
true
if this is a SUBSCRIBE packetSource§const IS_CONNECT: bool = false
const IS_CONNECT: bool = false
true
if this is a CONNECT packetSource§const IS_CONNACK: bool = false
const IS_CONNACK: bool = false
true
if this is a CONNACK packetSource§const IS_PUBLISH: bool = false
const IS_PUBLISH: bool = false
true
if this is a PUBLISH packetSource§const IS_PUBCOMP: bool = false
const IS_PUBCOMP: bool = false
true
if this is a PUBCOMP packetSource§const IS_UNSUBSCRIBE: bool = false
const IS_UNSUBSCRIBE: bool = false
true
if this is an UNSUBSCRIBE packetSource§const IS_UNSUBACK: bool = false
const IS_UNSUBACK: bool = false
true
if this is an UNSUBACK packetSource§const IS_PINGREQ: bool = false
const IS_PINGREQ: bool = false
true
if this is a PINGREQ packetSource§const IS_PINGRESP: bool = false
const IS_PINGRESP: bool = false
true
if this is a PINGRESP packetSource§const IS_DISCONNECT: bool = false
const IS_DISCONNECT: bool = false
true
if this is a DISCONNECT packetSource§impl<PacketIdType> PartialEq for GenericSubscribe<PacketIdType>
impl<PacketIdType> PartialEq for GenericSubscribe<PacketIdType>
Source§fn eq(&self, other: &GenericSubscribe<PacketIdType>) -> bool
fn eq(&self, other: &GenericSubscribe<PacketIdType>) -> bool
self
and other
values to be equal, and is used by ==
.Source§impl<PacketIdType> Serialize for GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
Serde Serialize trait implementation for SUBSCRIBE packets
impl<PacketIdType> Serialize for GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
Serde Serialize trait implementation for SUBSCRIBE packets
Serializes the SUBSCRIBE packet to a structured format (typically JSON) containing the packet type, packet identifier, properties (if any), and subscription entries (if any). Empty collections are omitted from the output.
§Serialized Fields
type
: Always “subscribe”packet_id
: The packet identifierprops
: Properties object (only if non-empty)entries
: Array of subscription entries (only if non-empty)
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::packet::qos::Qos;
use mqtt_protocol_core::mqtt::packet::SubEntry;
let subscribe = mqtt::packet::v5_0::Subscribe::builder()
.packet_id(123)
.entries(vec![
SubEntry::builder()
.topic_filter("home/sensor")
.unwrap()
.qos(Qos::ExactlyOnce)
.build()
.unwrap()
])
.build()
.unwrap();
let json = serde_json::to_string(&subscribe).unwrap();
// json contains: {"type":"subscribe","packet_id":123,"entries":[...]}
Source§impl<PacketIdType> TryInto<GenericSubscribe<PacketIdType>> for GenericPacket<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
impl<PacketIdType> TryInto<GenericSubscribe<PacketIdType>> for GenericPacket<PacketIdType>where
PacketIdType: IsPacketId + Serialize,
impl<PacketIdType> Eq for GenericSubscribe<PacketIdType>
impl<PacketIdType> SendableRole<Any> for GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId,
impl<PacketIdType> SendableRole<Client> for GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId,
impl<PacketIdType> StructuralPartialEq for GenericSubscribe<PacketIdType>where
PacketIdType: IsPacketId,
Auto Trait Implementations§
impl<PacketIdType> Freeze for GenericSubscribe<PacketIdType>
impl<PacketIdType> RefUnwindSafe for GenericSubscribe<PacketIdType>
impl<PacketIdType> Send for GenericSubscribe<PacketIdType>
impl<PacketIdType> Sync for GenericSubscribe<PacketIdType>
impl<PacketIdType> Unpin for GenericSubscribe<PacketIdType>
impl<PacketIdType> UnwindSafe for GenericSubscribe<PacketIdType>
Blanket Implementations§
Source§impl<T> AsConcrete<T> for T
impl<T> AsConcrete<T> for T
fn as_concrete(&self) -> Option<&T>
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key
and return true
if they are equal.