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
use super::*;
use alloc::string::String;
use alloc::vec::Vec;
use bytes::{Buf, Bytes};
#[derive(Debug, Clone, PartialEq)]
pub struct Unsubscribe {
pub pkid: u16,
pub topics: Vec<String>,
}
impl Unsubscribe {
pub fn new<S: Into<String>>(topic: S) -> Unsubscribe {
let mut topics = Vec::new();
topics.push(topic.into());
Unsubscribe { pkid: 0, topics }
}
pub fn read(fixed_header: FixedHeader, mut bytes: Bytes) -> Result<Self, Error> {
let variable_header_index = fixed_header.fixed_header_len;
bytes.advance(variable_header_index);
let pkid = read_u16(&mut bytes)?;
let mut payload_bytes = fixed_header.remaining_len - 2;
let mut topics = Vec::with_capacity(1);
while payload_bytes > 0 {
let topic_filter = read_mqtt_string(&mut bytes)?;
payload_bytes -= topic_filter.len() + 2;
topics.push(topic_filter);
}
let unsubscribe = Unsubscribe { pkid, topics };
Ok(unsubscribe)
}
pub fn write(&self, payload: &mut BytesMut) -> Result<usize, Error> {
let remaining_len = 2 + self
.topics
.iter()
.fold(0, |s, ref topic| s + topic.len() + 2);
payload.put_u8(0xA2);
let remaining_len_bytes = write_remaining_length(payload, remaining_len)?;
payload.put_u16(self.pkid);
for topic in self.topics.iter() {
write_mqtt_string(payload, topic.as_str());
}
Ok(1 + remaining_len_bytes + remaining_len)
}
}