[][src]Function mqttrs::encode

pub fn encode(packet: &Packet, buf: &mut impl BufMut) -> Result<(), Error>

Encode a Packet enum into a BufMut buffer.

// Instantiate a `Packet` to encode.
let packet = Publish {
   dup: false,
   qospid: QosPid::AtMostOnce,
   retain: false,
   topic_name: "test".into(),
   payload: "hello".into(),
}.into();

// Allocate buffer (should be appropriately-sized or able to grow as needed).
let mut buf = BytesMut::with_capacity(1024);

// Write bytes corresponding to `&Packet` into the `BytesMut`.
encode(&packet, &mut buf).expect("failed encoding");
assert_eq!(&*buf, &[0b00110000, 11,
                    0, 4, 't' as u8, 'e' as u8, 's' as u8, 't' as u8,
                   'h' as u8, 'e' as u8, 'l' as u8, 'l' as u8, 'o' as u8]);