mqtt_format/v3/
qos.rs

1//
2//   This Source Code Form is subject to the terms of the Mozilla Public
3//   License, v. 2.0. If a copy of the MPL was not distributed with this
4//   file, You can obtain one at http://mozilla.org/MPL/2.0/.
5//
6
7use futures::{AsyncWrite, AsyncWriteExt};
8
9use super::errors::{MPacketHeaderError, MPacketWriteError};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
12pub enum MQualityOfService {
13    AtMostOnce,
14    AtLeastOnce,
15    ExactlyOnce,
16}
17
18impl MQualityOfService {
19    pub fn to_byte(self) -> u8 {
20        match self {
21            MQualityOfService::AtMostOnce => 0x0,
22            MQualityOfService::AtLeastOnce => 0x1,
23            MQualityOfService::ExactlyOnce => 0x2,
24        }
25    }
26}
27
28pub fn mquality_of_service(lower: u8) -> Result<MQualityOfService, MPacketHeaderError> {
29    match lower {
30        0b00 => Ok(MQualityOfService::AtMostOnce),
31        0b01 => Ok(MQualityOfService::AtLeastOnce),
32        0b10 => Ok(MQualityOfService::ExactlyOnce),
33        inv_qos => Err(MPacketHeaderError::InvalidQualityOfService(inv_qos)),
34    }
35}
36impl MQualityOfService {
37    pub async fn write_to<W: AsyncWrite>(
38        &self,
39        writer: &mut std::pin::Pin<&mut W>,
40    ) -> Result<(), MPacketWriteError> {
41        writer
42            .write_all(match self {
43                MQualityOfService::AtMostOnce => &[0x0],
44                MQualityOfService::AtLeastOnce => &[0x1],
45                MQualityOfService::ExactlyOnce => &[0x2],
46            })
47            .await?;
48        Ok(())
49    }
50}