use core::convert::TryFrom;
use heapless::Vec;
use crate::{utils::*, MqttError, Pid};
use super::{property, PropertyType};
#[derive(Debug, Clone, PartialEq)]
pub struct PubComp<'a> {
pub pid: Pid,
pub reason: PubCompReason,
pub properties: Option<PubCompProperties<'a>>,
}
impl<'a> PubComp<'a> {
pub fn new(pid: Pid) -> Self {
PubComp {
pid,
reason: PubCompReason::Success,
properties: None,
}
}
pub fn read(buf: &'a [u8], offset: &mut usize) -> Result<Self, MqttError> {
let pid = Pid::read(buf, offset)?;
let reason = PubCompReason::try_from(buf[*offset])?;
*offset += 1;
Ok(PubComp {
pid,
reason,
properties: PubCompProperties::read(buf, offset)?,
})
}
pub fn write(&self, buf: &mut [u8], offset: &mut usize) -> Result<usize, MqttError> {
check_remaining(buf, offset, self.len())?;
let header: u8 = 0x70;
write_u8(buf, offset, header);
let write_len = write_length(buf, offset, self.len())?;
self.pid.write(buf, offset);
write_u8(buf, offset, self.reason as u8);
match &self.properties {
Some(properties) => properties.write(buf, offset)?,
None => write_u8(buf, offset, 0),
}
Ok(write_len)
}
fn len(&self) -> usize {
let mut len = 2 + 1;
if self.reason == PubCompReason::Success && self.properties.is_none() {
return 2;
}
match &self.properties {
Some(properties) => {
let properties_len = properties.len();
let properties_len_len = len_len(properties_len);
len += properties_len_len + properties_len;
}
None => {
len += 1;
}
}
len
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct PubCompProperties<'a> {
pub reason_string: Option<&'a str>,
pub user_properties: Vec<(&'a str, &'a str), 32>,
}
impl<'a> PubCompProperties<'a> {
pub fn read(buf: &'a [u8], offset: &mut usize) -> Result<Option<Self>, MqttError> {
let mut properties = Self::default();
let properties_len = buf[*offset];
if properties_len == 0 {
return Ok(None);
}
let mut cursor: usize = 1;
while cursor < properties_len.into() {
let mut prop_offset = *offset + cursor;
let prop = buf[prop_offset];
prop_offset += 1;
cursor += 1;
match property(prop)? {
PropertyType::ReasonString => {
let reason = read_str(buf, &mut prop_offset)?;
cursor += 2 + reason.len();
properties.reason_string = Some(reason);
}
PropertyType::UserProperty => {
let key = read_str(buf, &mut prop_offset)?;
let value = read_str(buf, &mut prop_offset)?;
cursor += 2 + key.len() + 2 + value.len();
properties
.user_properties
.push((key, value))
.map_err(|_| MqttError::TooManyUserProperties)?;
}
prop => return Err(MqttError::InvalidPropertyType(prop)),
}
}
*offset += properties.len();
Ok(Some(properties))
}
pub fn write(&self, buf: &mut [u8], offset: &mut usize) -> Result<(), MqttError> {
write_length(buf, offset, self.len())?;
if let Some(reason_string) = self.reason_string {
write_u8(buf, offset, PropertyType::ReasonString as u8);
write_bytes_with_len(buf, offset, reason_string.as_bytes());
}
for (key, value) in self.user_properties.iter() {
write_u8(buf, offset, PropertyType::UserProperty as u8);
write_bytes_with_len(buf, offset, key.as_bytes());
write_bytes_with_len(buf, offset, value.as_bytes());
}
Ok(())
}
fn len(&self) -> usize {
let mut len = 0;
if let Some(reason) = &self.reason_string {
len += 1 + 2 + reason.len();
}
for (key, value) in self.user_properties.iter() {
len += 1 + 2 + key.len() + 2 + value.len();
}
len
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(u8)]
pub enum PubCompReason {
Success = 0,
PacketIdentifierNotFound = 146,
}
impl TryFrom<u8> for PubCompReason {
type Error = MqttError;
fn try_from(value: u8) -> Result<Self, Self::Error> {
let code = match value {
0 => PubCompReason::Success,
146 => PubCompReason::PacketIdentifierNotFound,
code => return Err(MqttError::InvalidReasonCode(code)),
};
Ok(code)
}
}
#[cfg(test)]
mod test {
use crate::Pid;
use super::{PubComp, PubCompProperties, PubCompReason};
fn sample<'a>() -> PubComp<'a> {
let properties = PubCompProperties {
reason_string: Some("test"),
user_properties: heapless::Vec::<_, 32>::from_slice(&[("test", "test")]).unwrap(),
};
PubComp {
pid: Pid::new(42),
reason: PubCompReason::PacketIdentifierNotFound,
properties: Some(properties),
}
}
fn sample_bytes() -> Vec<u8> {
vec![
0x70, 0x18, 0x00, 0x2a, 0x92, 0x14, 0x1f, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x26, 0x00, 0x04, 0x74, 0x65, 0x73, 0x74, 0x00, 0x04, 0x74, 0x65, 0x73,
0x74, ]
}
#[test]
fn pubcomp_len() {
let expected = 24;
let actual = sample().len();
assert_eq!(expected, actual);
}
#[test]
fn pubcomp_encode() {
let expected = sample_bytes();
let mut buf = [0u8; 26];
sample().write(&mut buf, &mut 0).unwrap();
assert_eq!(expected.as_slice(), buf);
}
#[test]
fn pubcomp_decode() {
let bytes = &sample_bytes()[2..];
let expected = sample();
let actual = PubComp::read(bytes, &mut 0).unwrap();
assert_eq!(expected, actual);
}
#[test]
fn pubcomp_props_encode() {
let expected = &sample_bytes()[5..];
let mut buf = [0u8; 21];
sample()
.properties
.unwrap()
.write(&mut buf, &mut 0)
.unwrap();
assert_eq!(expected.len(), buf.len());
assert_eq!(expected, buf);
}
#[test]
fn pubcomp_props_decode() {
let bytes = &sample_bytes()[5..];
let expected = sample().properties.unwrap();
let actual = PubCompProperties::read(bytes, &mut 0).unwrap().unwrap();
assert_eq!(expected, actual);
}
fn sample2<'a>() -> PubComp<'a> {
PubComp {
pid: Pid::new(42),
reason: PubCompReason::PacketIdentifierNotFound,
properties: None,
}
}
fn sample_bytes2() -> Vec<u8> {
vec![
0x70, 0x04, 0x00, 0x2a, 0x92, 0x00, ]
}
#[test]
fn pubcomp_encode2() {
let expected = sample_bytes2();
let mut buf = [0u8; 6];
sample2().write(&mut buf, &mut 0).unwrap();
assert_eq!(expected.as_slice(), buf);
}
#[test]
fn pubcomp_decode2() {
let bytes = &sample_bytes2()[2..];
let expected = sample2();
let actual = PubComp::read(bytes, &mut 0).unwrap();
assert_eq!(expected, actual);
}
}