mqtt/control/variable_header/
protocol_level.rs

1//! Protocol level header
2
3use std::io::{self, Read, Write};
4
5use byteorder::{ReadBytesExt, WriteBytesExt};
6
7use crate::control::variable_header::VariableHeaderError;
8use crate::{Decodable, Encodable};
9
10pub const SPEC_3_1_0: u8 = 0x03;
11pub const SPEC_3_1_1: u8 = 0x04;
12pub const SPEC_5_0: u8 = 0x05;
13
14/// Protocol level in MQTT (`0x04` in v3.1.1)
15#[derive(Debug, Eq, PartialEq, Copy, Clone)]
16#[repr(u8)]
17pub enum ProtocolLevel {
18    Version310 = SPEC_3_1_0,
19    Version311 = SPEC_3_1_1,
20    Version50 = SPEC_5_0,
21}
22
23impl Encodable for ProtocolLevel {
24    fn encode<W: Write>(&self, writer: &mut W) -> Result<(), io::Error> {
25        writer.write_u8(*self as u8)
26    }
27
28    fn encoded_length(&self) -> u32 {
29        1
30    }
31}
32
33impl Decodable for ProtocolLevel {
34    type Error = VariableHeaderError;
35    type Cond = ();
36
37    fn decode_with<R: Read>(reader: &mut R, _rest: ()) -> Result<ProtocolLevel, VariableHeaderError> {
38        reader
39            .read_u8()
40            .map_err(From::from)
41            .map(ProtocolLevel::from_u8)
42            .and_then(|x| x.ok_or(VariableHeaderError::InvalidProtocolVersion))
43    }
44}
45
46impl ProtocolLevel {
47    pub fn from_u8(n: u8) -> Option<ProtocolLevel> {
48        match n {
49            SPEC_3_1_0 => Some(ProtocolLevel::Version310),
50            SPEC_3_1_1 => Some(ProtocolLevel::Version311),
51            SPEC_5_0 => Some(ProtocolLevel::Version50),
52            _ => None,
53        }
54    }
55}