use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use super::{ByteArray, DecodeError, EncodeError};
pub const PROTOCOL_NAME: &str = "MQTT";
pub const PROTOCOL_NAME_V3: &str = "MQIsdp";
pub trait EncodePacket {
fn encode(&self, v: &mut Vec<u8>) -> Result<usize, EncodeError>;
}
pub trait DecodePacket: Sized {
fn decode(ba: &mut ByteArray) -> Result<Self, DecodeError>;
}
#[repr(u8)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum QoS {
#[default]
AtMostOnce = 0,
AtLeastOnce = 1,
ExactOnce = 2,
}
impl QoS {
#[must_use]
pub const fn bytes() -> usize {
1
}
}
impl TryFrom<u8> for QoS {
type Error = DecodeError;
fn try_from(v: u8) -> Result<Self, Self::Error> {
match v {
0 => Ok(Self::AtMostOnce),
1 => Ok(Self::AtLeastOnce),
2 => Ok(Self::ExactOnce),
_ => Err(DecodeError::InvalidQoS),
}
}
}
impl EncodePacket for QoS {
fn encode(&self, v: &mut Vec<u8>) -> Result<usize, EncodeError> {
v.push(*self as u8);
Ok(Self::bytes())
}
}
impl DecodePacket for QoS {
fn decode(ba: &mut ByteArray) -> Result<Self, DecodeError> {
let byte = ba.read_byte()?;
let qos = Self::try_from(byte)?;
Ok(qos)
}
}