diff --git a/src/control/fixed_header.rs b/src/control/fixed_header.rs index cce640d..f45d738 100644 --- a/src/control/fixed_header.rs +++ b/src/control/fixed_header.rs @@ -38,10 +38,10 @@ pub struct FixedHeader { impl FixedHeader { pub fn new(packet_type: PacketType, remaining_length: u32) -> FixedHeader { - debug_assert!(remaining_length <= 0x0FFFFFFF); + debug_assert!(remaining_length <= 0x0FFF_FFFF); FixedHeader { - packet_type: packet_type, - remaining_length: remaining_length, + packet_type, + remaining_length, } } @@ -196,38 +196,28 @@ impl From for FixedHeaderError { impl fmt::Display for FixedHeaderError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &FixedHeaderError::MalformedRemainingLength => write!(f, "Malformed remaining length"), - &FixedHeaderError::Unrecognized(code, length) => { + match *self { + FixedHeaderError::MalformedRemainingLength => write!(f, "Malformed remaining length"), + FixedHeaderError::Unrecognized(code, length) => { write!(f, "Unrecognized header ({}, {})", code, length) } - &FixedHeaderError::ReservedType(code, length) => { + FixedHeaderError::ReservedType(code, length) => { write!(f, "Reserved header ({}, {})", code, length) } - &FixedHeaderError::PacketTypeError(ref err) => write!(f, "{}", err), - &FixedHeaderError::IoError(ref err) => write!(f, "{}", err), + FixedHeaderError::PacketTypeError(ref err) => write!(f, "{}", err), + FixedHeaderError::IoError(ref err) => write!(f, "{}", err), } } } impl Error for FixedHeaderError { - fn description(&self) -> &str { - match self { - &FixedHeaderError::MalformedRemainingLength => "Malformed remaining length", - &FixedHeaderError::Unrecognized(..) => "Unrecognized header", - &FixedHeaderError::ReservedType(..) => "Unrecognized header", - &FixedHeaderError::PacketTypeError(ref err) => err.description(), - &FixedHeaderError::IoError(ref err) => err.description(), - } - } - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - &FixedHeaderError::MalformedRemainingLength => None, - &FixedHeaderError::Unrecognized(..) => None, - &FixedHeaderError::ReservedType(..) => None, - &FixedHeaderError::PacketTypeError(ref err) => Some(err), - &FixedHeaderError::IoError(ref err) => Some(err), + match *self { + FixedHeaderError::MalformedRemainingLength => None, + FixedHeaderError::Unrecognized(..) => None, + FixedHeaderError::ReservedType(..) => None, + FixedHeaderError::PacketTypeError(ref err) => Some(err), + FixedHeaderError::IoError(ref err) => Some(err), } } } diff --git a/src/control/packet_type.rs b/src/control/packet_type.rs index 407c49d..2d6bd7f 100644 --- a/src/control/packet_type.rs +++ b/src/control/packet_type.rs @@ -11,7 +11,7 @@ pub struct PacketType { } /// Defined control types -#[cfg_attr(rustfmt, rustfmt_skip)] +#[rustfmt::skip] #[repr(u8)] #[derive(Debug, Eq, PartialEq, Copy, Clone)] pub enum ControlType { @@ -64,7 +64,7 @@ impl PacketType { pub fn new(t: ControlType, flags: u8) -> PacketType { PacketType { control_type: t, - flags: flags, + flags, } } @@ -97,12 +97,12 @@ impl PacketType { } /// To code - pub fn to_u8(&self) -> u8 { + pub fn to_u8(self) -> u8 { (self.control_type as u8) << 4 | (self.flags & 0x0F) } /// From code - #[cfg_attr(rustfmt, rustfmt_skip)] + #[rustfmt::skip] pub fn from_u8(val: u8) -> Result { let type_val = val >> 4; @@ -156,25 +156,23 @@ pub enum PacketTypeError { impl fmt::Display for PacketTypeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &PacketTypeError::ReservedType(t, flag) => write!(f, "Reserved type {:?} ({:#X})", t, flag), - &PacketTypeError::InvalidFlag(t, flag) => write!(f, "Invalid flag for {:?} ({:#X})", t, flag), - &PacketTypeError::UndefinedType(t, flag) => write!(f, "Undefined type {:?} ({:#X})", t, flag), + match *self { + PacketTypeError::ReservedType(t, flag) => { + write!(f, "Reserved type {:?} ({:#X})", t, flag) + } + PacketTypeError::InvalidFlag(t, flag) => { + write!(f, "Invalid flag for {:?} ({:#X})", t, flag) + } + PacketTypeError::UndefinedType(t, flag) => { + write!(f, "Undefined type {:?} ({:#X})", t, flag) + } } } } -impl Error for PacketTypeError { - fn description(&self) -> &str { - match self { - &PacketTypeError::ReservedType(..) => "Reserved type", - &PacketTypeError::UndefinedType(..) => "Undefined type", - &PacketTypeError::InvalidFlag(..) => "Invalid flag", - } - } -} +impl Error for PacketTypeError {} -#[cfg_attr(rustfmt, rustfmt_skip)] +#[rustfmt::skip] mod value { pub const CONNECT: u8 = 1; pub const CONNACK: u8 = 2; diff --git a/src/control/variable_header/connect_flags.rs b/src/control/variable_header/connect_flags.rs index 74ece49..f40d03c 100644 --- a/src/control/variable_header/connect_flags.rs +++ b/src/control/variable_header/connect_flags.rs @@ -3,8 +3,8 @@ use std::io::{Read, Write}; use byteorder::{ReadBytesExt, WriteBytesExt}; -use crate::{Decodable, Encodable}; use crate::control::variable_header::VariableHeaderError; +use crate::{Decodable, Encodable}; /// Flags for `CONNECT` packet #[derive(Debug, Eq, PartialEq, Copy, Clone)] @@ -33,7 +33,7 @@ impl ConnectFlags { impl Encodable for ConnectFlags { type Err = VariableHeaderError; - #[cfg_attr(rustfmt, rustfmt_skip)] + #[rustfmt::skip] fn encode(&self, writer: &mut W) -> Result<(), VariableHeaderError> { let code = ((self.user_name as u8) << 7) | ((self.password as u8) << 6) @@ -54,19 +54,22 @@ impl Decodable for ConnectFlags { type Err = VariableHeaderError; type Cond = (); - fn decode_with(reader: &mut R, _rest: Option<()>) -> Result { + fn decode_with( + reader: &mut R, + _rest: Option<()>, + ) -> Result { let code = reader.read_u8()?; if code & 1 != 0 { return Err(VariableHeaderError::InvalidReservedFlag); } Ok(ConnectFlags { - user_name: (code & 0b1000_0000) != 0, - password: (code & 0b0100_0000) != 0, - will_retain: (code & 0b0010_0000) != 0, - will_qos: (code & 0b0001_1000) >> 3, - will_flag: (code & 0b0000_0100) != 0, - clean_session: (code & 0b0000_0010) != 0, - }) + user_name: (code & 0b1000_0000) != 0, + password: (code & 0b0100_0000) != 0, + will_retain: (code & 0b0010_0000) != 0, + will_qos: (code & 0b0001_1000) >> 3, + will_flag: (code & 0b0000_0100) != 0, + clean_session: (code & 0b0000_0010) != 0, + }) } } diff --git a/src/control/variable_header/connect_ret_code.rs b/src/control/variable_header/connect_ret_code.rs index a85a60e..dd353f4 100644 --- a/src/control/variable_header/connect_ret_code.rs +++ b/src/control/variable_header/connect_ret_code.rs @@ -3,8 +3,8 @@ use std::io::{Read, Write}; use byteorder::{ReadBytesExt, WriteBytesExt}; -use crate::{Decodable, Encodable}; use crate::control::variable_header::VariableHeaderError; +use crate::{Decodable, Encodable}; pub const CONNECTION_ACCEPTED: u8 = 0x00; pub const UNACCEPTABLE_PROTOCOL_VERSION: u8 = 0x01; @@ -27,8 +27,8 @@ pub enum ConnectReturnCode { impl ConnectReturnCode { /// Get the code - pub fn to_u8(&self) -> u8 { - match *self { + pub fn to_u8(self) -> u8 { + match self { ConnectReturnCode::ConnectionAccepted => CONNECTION_ACCEPTED, ConnectReturnCode::UnacceptableProtocolVersion => UNACCEPTABLE_PROTOCOL_VERSION, ConnectReturnCode::IdentifierRejected => IDENTIFIER_REJECTED, @@ -69,9 +69,13 @@ impl Decodable for ConnectReturnCode { type Err = VariableHeaderError; type Cond = (); - fn decode_with(reader: &mut R, _rest: Option<()>) -> Result { - reader.read_u8() - .map(ConnectReturnCode::from_u8) - .map_err(From::from) + fn decode_with( + reader: &mut R, + _rest: Option<()>, + ) -> Result { + reader + .read_u8() + .map(ConnectReturnCode::from_u8) + .map_err(From::from) } } diff --git a/src/control/variable_header/mod.rs b/src/control/variable_header/mod.rs index 1e425a9..6b6b7be 100644 --- a/src/control/variable_header/mod.rs +++ b/src/control/variable_header/mod.rs @@ -18,13 +18,13 @@ pub use self::protocol_level::ProtocolLevel; pub use self::protocol_name::ProtocolName; pub use self::topic_name::TopicNameHeader; -mod packet_identifier; -mod protocol_name; -pub mod protocol_level; -mod connect_flags; -mod keep_alive; mod connect_ack_flags; +mod connect_flags; mod connect_ret_code; +mod keep_alive; +mod packet_identifier; +pub mod protocol_level; +mod protocol_name; mod topic_name; /// Errors while decoding variable header @@ -63,34 +63,24 @@ impl From for VariableHeaderError { impl fmt::Display for VariableHeaderError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &VariableHeaderError::IoError(ref err) => write!(f, "{}", err), - &VariableHeaderError::StringEncodeError(ref err) => write!(f, "{}", err), - &VariableHeaderError::InvalidReservedFlag => write!(f, "Invalid reserved flags"), - &VariableHeaderError::FromUtf8Error(ref err) => write!(f, "{}", err), - &VariableHeaderError::TopicNameError(ref err) => write!(f, "{}", err), + match *self { + VariableHeaderError::IoError(ref err) => write!(f, "{}", err), + VariableHeaderError::StringEncodeError(ref err) => write!(f, "{}", err), + VariableHeaderError::InvalidReservedFlag => write!(f, "Invalid reserved flags"), + VariableHeaderError::FromUtf8Error(ref err) => write!(f, "{}", err), + VariableHeaderError::TopicNameError(ref err) => write!(f, "{}", err), } } } impl Error for VariableHeaderError { - fn description(&self) -> &str { - match self { - &VariableHeaderError::IoError(ref err) => err.description(), - &VariableHeaderError::StringEncodeError(ref err) => err.description(), - &VariableHeaderError::InvalidReservedFlag => "Invalid reserved flags", - &VariableHeaderError::FromUtf8Error(ref err) => err.description(), - &VariableHeaderError::TopicNameError(ref err) => err.description(), - } - } - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - &VariableHeaderError::IoError(ref err) => Some(err), - &VariableHeaderError::StringEncodeError(ref err) => Some(err), - &VariableHeaderError::InvalidReservedFlag => None, - &VariableHeaderError::FromUtf8Error(ref err) => Some(err), - &VariableHeaderError::TopicNameError(ref err) => Some(err), + match *self { + VariableHeaderError::IoError(ref err) => Some(err), + VariableHeaderError::StringEncodeError(ref err) => Some(err), + VariableHeaderError::InvalidReservedFlag => None, + VariableHeaderError::FromUtf8Error(ref err) => Some(err), + VariableHeaderError::TopicNameError(ref err) => Some(err), } } } diff --git a/src/encodable.rs b/src/encodable.rs index 34cee89..3ec2e32 100644 --- a/src/encodable.rs +++ b/src/encodable.rs @@ -39,10 +39,11 @@ impl<'a> Encodable for &'a str { fn encode(&self, writer: &mut W) -> Result<(), StringEncodeError> { assert!(self.as_bytes().len() <= u16::max_value() as usize); - writer.write_u16::(self.as_bytes().len() as u16) - .map_err(From::from) - .and_then(|_| writer.write_all(self.as_bytes())) - .map_err(StringEncodeError::IoError) + writer + .write_u16::(self.as_bytes().len() as u16) + .map_err(From::from) + .and_then(|_| writer.write_all(self.as_bytes())) + .map_err(StringEncodeError::IoError) } fn encoded_length(&self) -> u32 { @@ -78,7 +79,10 @@ impl Decodable for String { type Err = StringEncodeError; type Cond = (); - fn decode_with(reader: &mut R, _rest: Option<()>) -> Result { + fn decode_with( + reader: &mut R, + _rest: Option<()>, + ) -> Result { let len = reader.read_u16::()? as usize; let mut buf = Vec::with_capacity(len); unsafe { @@ -205,28 +209,20 @@ pub enum StringEncodeError { impl fmt::Display for StringEncodeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &StringEncodeError::IoError(ref err) => err.fmt(f), - &StringEncodeError::FromUtf8Error(ref err) => err.fmt(f), - &StringEncodeError::MalformedData => write!(f, "Malformed data"), + match *self { + StringEncodeError::IoError(ref err) => err.fmt(f), + StringEncodeError::FromUtf8Error(ref err) => err.fmt(f), + StringEncodeError::MalformedData => write!(f, "Malformed data"), } } } impl Error for StringEncodeError { - fn description(&self) -> &str { - match self { - &StringEncodeError::IoError(ref err) => err.description(), - &StringEncodeError::FromUtf8Error(ref err) => err.description(), - &StringEncodeError::MalformedData => "Malformed data", - } - } - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - &StringEncodeError::IoError(ref err) => Some(err), - &StringEncodeError::FromUtf8Error(ref err) => Some(err), - &StringEncodeError::MalformedData => None, + match *self { + StringEncodeError::IoError(ref err) => Some(err), + StringEncodeError::FromUtf8Error(ref err) => Some(err), + StringEncodeError::MalformedData => None, } } } diff --git a/src/packet/connack.rs b/src/packet/connack.rs index ea78f0f..b5c8bf9 100644 --- a/src/packet/connack.rs +++ b/src/packet/connack.rs @@ -2,10 +2,10 @@ use std::io::{Read, Write}; -use crate::{Decodable, Encodable}; -use crate::control::{ControlType, FixedHeader, PacketType}; use crate::control::variable_header::{ConnackFlags, ConnectReturnCode}; +use crate::control::{ControlType, FixedHeader, PacketType}; use crate::packet::{Packet, PacketError}; +use crate::{Decodable, Encodable}; /// `CONNACK` packet #[derive(Debug, Eq, PartialEq, Clone)] @@ -19,9 +19,12 @@ pub struct ConnackPacket { impl ConnackPacket { pub fn new(session_present: bool, ret_code: ConnectReturnCode) -> ConnackPacket { ConnackPacket { - fixed_header: FixedHeader::new(PacketType::with_default(ControlType::ConnectAcknowledgement), 2), - flags: ConnackFlags { session_present: session_present }, - ret_code: ret_code, + fixed_header: FixedHeader::new( + PacketType::with_default(ControlType::ConnectAcknowledgement), + 2, + ), + flags: ConnackFlags { session_present }, + ret_code, payload: (), } } @@ -60,16 +63,19 @@ impl Packet for ConnackPacket { self.flags.encoded_length() + self.ret_code.encoded_length() } - fn decode_packet(reader: &mut R, fixed_header: FixedHeader) -> Result> { + fn decode_packet( + reader: &mut R, + fixed_header: FixedHeader, + ) -> Result> { let flags: ConnackFlags = Decodable::decode(reader)?; let code: ConnectReturnCode = Decodable::decode(reader)?; Ok(ConnackPacket { - fixed_header: fixed_header, - flags: flags, - ret_code: code, - payload: (), - }) + fixed_header, + flags, + ret_code: code, + payload: (), + }) } } @@ -79,8 +85,8 @@ mod test { use std::io::Cursor; - use crate::{Decodable, Encodable}; use crate::control::variable_header::ConnectReturnCode; + use crate::{Decodable, Encodable}; #[test] pub fn test_connack_packet_basic() { diff --git a/src/packet/connect.rs b/src/packet/connect.rs index bbbfbe2..4f58e7c 100644 --- a/src/packet/connect.rs +++ b/src/packet/connect.rs @@ -4,13 +4,13 @@ use std::error::Error; use std::fmt; use std::io::{self, Read, Write}; -use crate::{Decodable, Encodable}; -use crate::control::{ControlType, FixedHeader, PacketType}; -use crate::control::variable_header::{ConnectFlags, KeepAlive, ProtocolLevel, ProtocolName}; use crate::control::variable_header::protocol_level::SPEC_3_1_1; +use crate::control::variable_header::{ConnectFlags, KeepAlive, ProtocolLevel, ProtocolName}; +use crate::control::{ControlType, FixedHeader, PacketType}; use crate::encodable::{StringEncodeError, VarBytes}; use crate::packet::{Packet, PacketError}; use crate::topic_name::{TopicName, TopicNameError}; +use crate::{Decodable, Encodable}; /// `CONNECT` packet #[derive(Debug, Eq, PartialEq, Clone)] @@ -123,11 +123,11 @@ impl ConnectPacket { .as_ref() .map(|x| &x[..]) .and_then(|topic| { - self.payload - .will_message - .as_ref() - .map(|msg| (topic, &msg.0)) - }) + self.payload + .will_message + .as_ref() + .map(|msg| (topic, &msg.0)) + }) } pub fn will_retain(&self) -> bool { @@ -172,26 +172,31 @@ impl Packet for ConnectPacket { } fn encoded_variable_headers_length(&self) -> u32 { - self.protocol_name.encoded_length() + self.protocol_level.encoded_length() + self.flags.encoded_length() + - self.keep_alive.encoded_length() + self.protocol_name.encoded_length() + + self.protocol_level.encoded_length() + + self.flags.encoded_length() + + self.keep_alive.encoded_length() } - fn decode_packet(reader: &mut R, fixed_header: FixedHeader) -> Result> { + fn decode_packet( + reader: &mut R, + fixed_header: FixedHeader, + ) -> Result> { let protoname: ProtocolName = Decodable::decode(reader)?; let protocol_level: ProtocolLevel = Decodable::decode(reader)?; let flags: ConnectFlags = Decodable::decode(reader)?; let keep_alive: KeepAlive = Decodable::decode(reader)?; - let payload: ConnectPacketPayload = Decodable::decode_with(reader, Some(flags)) - .map_err(PacketError::PayloadError)?; + let payload: ConnectPacketPayload = + Decodable::decode_with(reader, Some(flags)).map_err(PacketError::PayloadError)?; Ok(ConnectPacket { - fixed_header: fixed_header, - protocol_name: protoname, - protocol_level: protocol_level, - flags: flags, - keep_alive: keep_alive, - payload: payload, - }) + fixed_header, + protocol_name: protoname, + protocol_level, + flags, + keep_alive, + payload, + }) } } @@ -208,7 +213,7 @@ pub struct ConnectPacketPayload { impl ConnectPacketPayload { pub fn new(client_identifier: String) -> ConnectPacketPayload { ConnectPacketPayload { - client_identifier: client_identifier, + client_identifier, will_topic: None, will_message: None, user_name: None, @@ -243,20 +248,24 @@ impl Encodable for ConnectPacketPayload { } fn encoded_length(&self) -> u32 { - self.client_identifier.encoded_length() + - self.will_topic + self.client_identifier.encoded_length() + + self + .will_topic .as_ref() .map(|t| t.encoded_length()) - .unwrap_or(0) + - self.will_message + .unwrap_or(0) + + self + .will_message .as_ref() .map(|t| t.encoded_length()) - .unwrap_or(0) + - self.user_name + .unwrap_or(0) + + self + .user_name .as_ref() .map(|t| t.encoded_length()) - .unwrap_or(0) + - self.password + .unwrap_or(0) + + self + .password .as_ref() .map(|t| t.encoded_length()) .unwrap_or(0) @@ -267,9 +276,10 @@ impl Decodable for ConnectPacketPayload { type Err = ConnectPacketPayloadError; type Cond = ConnectFlags; - fn decode_with(reader: &mut R, - rest: Option) - -> Result { + fn decode_with( + reader: &mut R, + rest: Option, + ) -> Result { let mut need_will_topic = false; let mut need_will_message = false; let mut need_user_name = false; @@ -305,12 +315,12 @@ impl Decodable for ConnectPacketPayload { }; Ok(ConnectPacketPayload { - client_identifier: ident, - will_topic: topic, - will_message: msg, - user_name: uname, - password: pwd, - }) + client_identifier: ident, + will_topic: topic, + will_message: msg, + user_name: uname, + password: pwd, + }) } } @@ -323,28 +333,20 @@ pub enum ConnectPacketPayloadError { impl fmt::Display for ConnectPacketPayloadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &ConnectPacketPayloadError::IoError(ref err) => err.fmt(f), - &ConnectPacketPayloadError::StringEncodeError(ref err) => err.fmt(f), - &ConnectPacketPayloadError::TopicNameError(ref err) => err.fmt(f), + match *self { + ConnectPacketPayloadError::IoError(ref err) => err.fmt(f), + ConnectPacketPayloadError::StringEncodeError(ref err) => err.fmt(f), + ConnectPacketPayloadError::TopicNameError(ref err) => err.fmt(f), } } } impl Error for ConnectPacketPayloadError { - fn description(&self) -> &str { - match self { - &ConnectPacketPayloadError::IoError(ref err) => err.description(), - &ConnectPacketPayloadError::StringEncodeError(ref err) => err.description(), - &ConnectPacketPayloadError::TopicNameError(ref err) => err.description(), - } - } - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - &ConnectPacketPayloadError::IoError(ref err) => Some(err), - &ConnectPacketPayloadError::StringEncodeError(ref err) => Some(err), - &ConnectPacketPayloadError::TopicNameError(ref err) => Some(err), + match *self { + ConnectPacketPayloadError::IoError(ref err) => Some(err), + ConnectPacketPayloadError::StringEncodeError(ref err) => Some(err), + ConnectPacketPayloadError::TopicNameError(ref err) => Some(err), } } } diff --git a/src/packet/disconnect.rs b/src/packet/disconnect.rs index 85932f1..3c44174 100644 --- a/src/packet/disconnect.rs +++ b/src/packet/disconnect.rs @@ -21,6 +21,12 @@ impl DisconnectPacket { } } +impl Default for DisconnectPacket { + fn default() -> DisconnectPacket { + DisconnectPacket::new() + } +} + impl Packet for DisconnectPacket { type Payload = (); @@ -44,10 +50,13 @@ impl Packet for DisconnectPacket { 0 } - fn decode_packet(_reader: &mut R, fixed_header: FixedHeader) -> Result> { + fn decode_packet( + _reader: &mut R, + fixed_header: FixedHeader, + ) -> Result> { Ok(DisconnectPacket { - fixed_header: fixed_header, - payload: (), - }) + fixed_header, + payload: (), + }) } } diff --git a/src/packet/mod.rs b/src/packet/mod.rs index 9141853..d877893 100644 --- a/src/packet/mod.rs +++ b/src/packet/mod.rs @@ -121,40 +121,28 @@ pub enum PacketError { impl fmt::Display for PacketError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &PacketError::FixedHeaderError(ref err) => err.fmt(f), - &PacketError::VariableHeaderError(ref err) => err.fmt(f), - &PacketError::PayloadError(ref err) => err.fmt(f), - &PacketError::MalformedPacket(ref err) => err.fmt(f), - &PacketError::StringEncodeError(ref err) => err.fmt(f), - &PacketError::IoError(ref err) => err.fmt(f), - &PacketError::TopicNameError(ref err) => err.fmt(f), + match *self { + PacketError::FixedHeaderError(ref err) => err.fmt(f), + PacketError::VariableHeaderError(ref err) => err.fmt(f), + PacketError::PayloadError(ref err) => err.fmt(f), + PacketError::MalformedPacket(ref err) => err.fmt(f), + PacketError::StringEncodeError(ref err) => err.fmt(f), + PacketError::IoError(ref err) => err.fmt(f), + PacketError::TopicNameError(ref err) => err.fmt(f), } } } impl Error for PacketError { - fn description(&self) -> &str { - match self { - &PacketError::FixedHeaderError(ref err) => err.description(), - &PacketError::VariableHeaderError(ref err) => err.description(), - &PacketError::PayloadError(ref err) => err.description(), - &PacketError::MalformedPacket(ref err) => &err[..], - &PacketError::StringEncodeError(ref err) => err.description(), - &PacketError::IoError(ref err) => err.description(), - &PacketError::TopicNameError(ref err) => err.description(), - } - } - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - &PacketError::FixedHeaderError(ref err) => Some(err), - &PacketError::VariableHeaderError(ref err) => Some(err), - &PacketError::PayloadError(ref err) => Some(err), - &PacketError::MalformedPacket(..) => None, - &PacketError::StringEncodeError(ref err) => Some(err), - &PacketError::IoError(ref err) => Some(err), - &PacketError::TopicNameError(ref err) => Some(err), + match *self { + PacketError::FixedHeaderError(ref err) => Some(err), + PacketError::VariableHeaderError(ref err) => Some(err), + PacketError::PayloadError(ref err) => Some(err), + PacketError::MalformedPacket(..) => None, + PacketError::StringEncodeError(ref err) => Some(err), + PacketError::IoError(ref err) => Some(err), + PacketError::TopicNameError(ref err) => Some(err), } } } @@ -281,17 +269,17 @@ macro_rules! impl_variable_packet { type Err = VariablePacketError; fn encode(&self, writer: &mut W) -> Result<(), VariablePacketError> { - match self { + match *self { $( - &VariablePacket::$name(ref pk) => pk.encode(writer).map_err(From::from), + VariablePacket::$name(ref pk) => pk.encode(writer).map_err(From::from), )+ } } fn encoded_length(&self) -> u32 { - match self { + match *self { $( - &VariablePacket::$name(ref pk) => pk.encoded_length(), + VariablePacket::$name(ref pk) => pk.encoded_length(), )+ } } @@ -371,41 +359,29 @@ macro_rules! impl_variable_packet { impl fmt::Display for VariablePacketError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &VariablePacketError::FixedHeaderError(ref err) => err.fmt(f), - &VariablePacketError::UnrecognizedPacket(ref code, ref v) => + match *self { + VariablePacketError::FixedHeaderError(ref err) => err.fmt(f), + VariablePacketError::UnrecognizedPacket(ref code, ref v) => write!(f, "Unrecognized type ({}), [u8, ..{}]", code, v.len()), - &VariablePacketError::ReservedPacket(ref code, ref v) => + VariablePacketError::ReservedPacket(ref code, ref v) => write!(f, "Reserved type ({}), [u8, ..{}]", code, v.len()), - &VariablePacketError::IoError(ref err) => err.fmt(f), + VariablePacketError::IoError(ref err) => err.fmt(f), $( - &VariablePacketError::$errname(ref err) => err.fmt(f), + VariablePacketError::$errname(ref err) => err.fmt(f), )+ } } } impl Error for VariablePacketError { - fn description(&self) -> &str { - match self { - &VariablePacketError::FixedHeaderError(ref err) => err.description(), - &VariablePacketError::UnrecognizedPacket(..) => "Unrecognized packet", - &VariablePacketError::ReservedPacket(..) => "Reserved packet", - &VariablePacketError::IoError(ref err) => err.description(), - $( - &VariablePacketError::$errname(ref err) => err.description(), - )+ - } - } - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - &VariablePacketError::FixedHeaderError(ref err) => Some(err), - &VariablePacketError::UnrecognizedPacket(..) => None, - &VariablePacketError::ReservedPacket(..) => None, - &VariablePacketError::IoError(ref err) => Some(err), + match *self { + VariablePacketError::FixedHeaderError(ref err) => Some(err), + VariablePacketError::UnrecognizedPacket(..) => None, + VariablePacketError::ReservedPacket(..) => None, + VariablePacketError::IoError(ref err) => Some(err), $( - &VariablePacketError::$errname(ref err) => Some(err), + VariablePacketError::$errname(ref err) => Some(err), )+ } } diff --git a/src/packet/pingreq.rs b/src/packet/pingreq.rs index 48ff382..3c6f864 100644 --- a/src/packet/pingreq.rs +++ b/src/packet/pingreq.rs @@ -21,6 +21,12 @@ impl PingreqPacket { } } +impl Default for PingreqPacket { + fn default() -> PingreqPacket { + PingreqPacket::new() + } +} + impl Packet for PingreqPacket { type Payload = (); @@ -44,10 +50,13 @@ impl Packet for PingreqPacket { 0 } - fn decode_packet(_reader: &mut R, fixed_header: FixedHeader) -> Result> { + fn decode_packet( + _reader: &mut R, + fixed_header: FixedHeader, + ) -> Result> { Ok(PingreqPacket { - fixed_header: fixed_header, - payload: (), - }) + fixed_header, + payload: (), + }) } } diff --git a/src/packet/pingresp.rs b/src/packet/pingresp.rs index bb18571..a98511b 100644 --- a/src/packet/pingresp.rs +++ b/src/packet/pingresp.rs @@ -21,6 +21,12 @@ impl PingrespPacket { } } +impl Default for PingrespPacket { + fn default() -> PingrespPacket { + PingrespPacket::new() + } +} + impl Packet for PingrespPacket { type Payload = (); @@ -44,10 +50,13 @@ impl Packet for PingrespPacket { 0 } - fn decode_packet(_reader: &mut R, fixed_header: FixedHeader) -> Result> { + fn decode_packet( + _reader: &mut R, + fixed_header: FixedHeader, + ) -> Result> { Ok(PingrespPacket { - fixed_header: fixed_header, - payload: (), - }) + fixed_header, + payload: (), + }) } } diff --git a/src/packet/puback.rs b/src/packet/puback.rs index 6e260b6..93af56a 100644 --- a/src/packet/puback.rs +++ b/src/packet/puback.rs @@ -2,10 +2,10 @@ use std::io::{Read, Write}; -use crate::{Decodable, Encodable}; -use crate::control::{ControlType, FixedHeader, PacketType}; use crate::control::variable_header::PacketIdentifier; +use crate::control::{ControlType, FixedHeader, PacketType}; use crate::packet::{Packet, PacketError}; +use crate::{Decodable, Encodable}; /// `PUBACK` packet #[derive(Debug, Eq, PartialEq, Clone)] @@ -18,7 +18,10 @@ pub struct PubackPacket { impl PubackPacket { pub fn new(pkid: u16) -> PubackPacket { PubackPacket { - fixed_header: FixedHeader::new(PacketType::with_default(ControlType::PublishAcknowledgement), 2), + fixed_header: FixedHeader::new( + PacketType::with_default(ControlType::PublishAcknowledgement), + 2, + ), packet_identifier: PacketIdentifier(pkid), payload: (), } @@ -58,12 +61,15 @@ impl Packet for PubackPacket { self.packet_identifier.encoded_length() } - fn decode_packet(reader: &mut R, fixed_header: FixedHeader) -> Result> { + fn decode_packet( + reader: &mut R, + fixed_header: FixedHeader, + ) -> Result> { let packet_identifier: PacketIdentifier = PacketIdentifier::decode(reader)?; Ok(PubackPacket { - fixed_header: fixed_header, - packet_identifier: packet_identifier, - payload: (), - }) + fixed_header, + packet_identifier, + payload: (), + }) } } diff --git a/src/packet/pubcomp.rs b/src/packet/pubcomp.rs index 48cd132..b3f9ab6 100644 --- a/src/packet/pubcomp.rs +++ b/src/packet/pubcomp.rs @@ -2,10 +2,10 @@ use std::io::{Read, Write}; -use crate::{Decodable, Encodable}; -use crate::control::{ControlType, FixedHeader, PacketType}; use crate::control::variable_header::PacketIdentifier; +use crate::control::{ControlType, FixedHeader, PacketType}; use crate::packet::{Packet, PacketError}; +use crate::{Decodable, Encodable}; /// `PUBCOMP` packet #[derive(Debug, Eq, PartialEq, Clone)] @@ -18,7 +18,10 @@ pub struct PubcompPacket { impl PubcompPacket { pub fn new(pkid: u16) -> PubcompPacket { PubcompPacket { - fixed_header: FixedHeader::new(PacketType::with_default(ControlType::PublishComplete), 2), + fixed_header: FixedHeader::new( + PacketType::with_default(ControlType::PublishComplete), + 2, + ), packet_identifier: PacketIdentifier(pkid), payload: (), } @@ -58,12 +61,15 @@ impl Packet for PubcompPacket { self.packet_identifier.encoded_length() } - fn decode_packet(reader: &mut R, fixed_header: FixedHeader) -> Result> { + fn decode_packet( + reader: &mut R, + fixed_header: FixedHeader, + ) -> Result> { let packet_identifier: PacketIdentifier = PacketIdentifier::decode(reader)?; Ok(PubcompPacket { - fixed_header: fixed_header, - packet_identifier: packet_identifier, - payload: (), - }) + fixed_header, + packet_identifier, + payload: (), + }) } } diff --git a/src/packet/publish.rs b/src/packet/publish.rs index eee44a9..8b2cb32 100644 --- a/src/packet/publish.rs +++ b/src/packet/publish.rs @@ -2,12 +2,12 @@ use std::io::{Read, Write}; -use crate::{Decodable, Encodable}; -use crate::control::{ControlType, FixedHeader, PacketType}; use crate::control::variable_header::PacketIdentifier; +use crate::control::{ControlType, FixedHeader, PacketType}; use crate::packet::{Packet, PacketError}; use crate::qos::QualityOfService; use crate::topic_name::TopicName; +use crate::{Decodable, Encodable}; /// QoS with identifier pairs #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Copy, Clone)] @@ -37,7 +37,11 @@ pub struct PublishPacket { } impl PublishPacket { - pub fn new>>(topic_name: TopicName, qos: QoSWithPacketIdentifier, payload: P) -> PublishPacket { + pub fn new>>( + topic_name: TopicName, + qos: QoSWithPacketIdentifier, + payload: P, + ) -> PublishPacket { let (qos, pkid) = match qos { QoSWithPacketIdentifier::Level0 => (0, None), QoSWithPacketIdentifier::Level1(pkid) => (1, Some(PacketIdentifier(pkid))), @@ -46,7 +50,7 @@ impl PublishPacket { let mut pk = PublishPacket { fixed_header: FixedHeader::new(PacketType::with_default(ControlType::Publish), 0), - topic_name: topic_name, + topic_name, packet_identifier: pkid, payload: payload.into(), }; @@ -136,14 +140,18 @@ impl Packet for PublishPacket { } fn encoded_variable_headers_length(&self) -> u32 { - self.topic_name.encoded_length() + - self.packet_identifier + self.topic_name.encoded_length() + + self + .packet_identifier .as_ref() .map(|x| x.encoded_length()) .unwrap_or(0) } - fn decode_packet(reader: &mut R, fixed_header: FixedHeader) -> Result> { + fn decode_packet( + reader: &mut R, + fixed_header: FixedHeader, + ) -> Result> { let topic_name: TopicName = TopicName::decode(reader)?; let packet_identifier = if fixed_header.packet_type.flags & 0x06 != 0 { @@ -152,20 +160,21 @@ impl Packet for PublishPacket { None }; - let vhead_len = topic_name.encoded_length() + - packet_identifier.as_ref() - .map(|x| x.encoded_length()) - .unwrap_or(0); + let vhead_len = topic_name.encoded_length() + + packet_identifier + .as_ref() + .map(|x| x.encoded_length()) + .unwrap_or(0); let payload_len = fixed_header.remaining_length - vhead_len; let payload: Vec = Decodable::decode_with(reader, Some(payload_len))?; Ok(PublishPacket { - fixed_header: fixed_header, - topic_name: topic_name, - packet_identifier: packet_identifier, - payload: payload, - }) + fixed_header, + topic_name, + packet_identifier, + payload, + }) } } @@ -175,14 +184,16 @@ mod test { use std::io::Cursor; - use crate::{Decodable, Encodable}; use crate::topic_name::TopicName; + use crate::{Decodable, Encodable}; #[test] fn test_publish_packet_basic() { - let packet = PublishPacket::new(TopicName::new("a/b".to_owned()).unwrap(), - QoSWithPacketIdentifier::Level2(10), - b"Hello world!".to_vec()); + let packet = PublishPacket::new( + TopicName::new("a/b".to_owned()).unwrap(), + QoSWithPacketIdentifier::Level2(10), + b"Hello world!".to_vec(), + ); let mut buf = Vec::new(); packet.encode(&mut buf).unwrap(); diff --git a/src/packet/pubrec.rs b/src/packet/pubrec.rs index 360e3bf..342159e 100644 --- a/src/packet/pubrec.rs +++ b/src/packet/pubrec.rs @@ -2,10 +2,10 @@ use std::io::{Read, Write}; -use crate::{Decodable, Encodable}; -use crate::control::{ControlType, FixedHeader, PacketType}; use crate::control::variable_header::PacketIdentifier; +use crate::control::{ControlType, FixedHeader, PacketType}; use crate::packet::{Packet, PacketError}; +use crate::{Decodable, Encodable}; /// `PUBREC` packet #[derive(Debug, Eq, PartialEq, Clone)] @@ -18,7 +18,10 @@ pub struct PubrecPacket { impl PubrecPacket { pub fn new(pkid: u16) -> PubrecPacket { PubrecPacket { - fixed_header: FixedHeader::new(PacketType::with_default(ControlType::PublishReceived), 2), + fixed_header: FixedHeader::new( + PacketType::with_default(ControlType::PublishReceived), + 2, + ), packet_identifier: PacketIdentifier(pkid), payload: (), } @@ -58,12 +61,15 @@ impl Packet for PubrecPacket { self.packet_identifier.encoded_length() } - fn decode_packet(reader: &mut R, fixed_header: FixedHeader) -> Result> { + fn decode_packet( + reader: &mut R, + fixed_header: FixedHeader, + ) -> Result> { let packet_identifier: PacketIdentifier = PacketIdentifier::decode(reader)?; Ok(PubrecPacket { - fixed_header: fixed_header, - packet_identifier: packet_identifier, - payload: (), - }) + fixed_header, + packet_identifier, + payload: (), + }) } } diff --git a/src/packet/pubrel.rs b/src/packet/pubrel.rs index 2260f1e..6589e9a 100644 --- a/src/packet/pubrel.rs +++ b/src/packet/pubrel.rs @@ -2,10 +2,10 @@ use std::io::{Read, Write}; -use crate::{Decodable, Encodable}; -use crate::control::{ControlType, FixedHeader, PacketType}; use crate::control::variable_header::PacketIdentifier; +use crate::control::{ControlType, FixedHeader, PacketType}; use crate::packet::{Packet, PacketError}; +use crate::{Decodable, Encodable}; /// `PUBREL` packet #[derive(Debug, Eq, PartialEq, Clone)] @@ -18,7 +18,10 @@ pub struct PubrelPacket { impl PubrelPacket { pub fn new(pkid: u16) -> PubrelPacket { PubrelPacket { - fixed_header: FixedHeader::new(PacketType::with_default(ControlType::PublishRelease), 2), + fixed_header: FixedHeader::new( + PacketType::with_default(ControlType::PublishRelease), + 2, + ), packet_identifier: PacketIdentifier(pkid), payload: (), } @@ -58,12 +61,15 @@ impl Packet for PubrelPacket { self.packet_identifier.encoded_length() } - fn decode_packet(reader: &mut R, fixed_header: FixedHeader) -> Result> { + fn decode_packet( + reader: &mut R, + fixed_header: FixedHeader, + ) -> Result> { let packet_identifier: PacketIdentifier = PacketIdentifier::decode(reader)?; Ok(PubrelPacket { - fixed_header: fixed_header, - packet_identifier: packet_identifier, - payload: (), - }) + fixed_header, + packet_identifier, + payload: (), + }) } } diff --git a/src/packet/suback.rs b/src/packet/suback.rs index 4297dd9..1daa6f3 100644 --- a/src/packet/suback.rs +++ b/src/packet/suback.rs @@ -8,11 +8,11 @@ use std::io::{self, Read, Write}; use byteorder::{ReadBytesExt, WriteBytesExt}; -use crate::{Decodable, Encodable}; -use crate::control::{ControlType, FixedHeader, PacketType}; use crate::control::variable_header::PacketIdentifier; +use crate::control::{ControlType, FixedHeader, PacketType}; use crate::packet::{Packet, PacketError}; use crate::qos::QualityOfService; +use crate::{Decodable, Encodable}; /// Subscribe code #[repr(u8)] @@ -62,11 +62,15 @@ pub struct SubackPacket { impl SubackPacket { pub fn new(pkid: u16, subscribes: Vec) -> SubackPacket { let mut pk = SubackPacket { - fixed_header: FixedHeader::new(PacketType::with_default(ControlType::SubscribeAcknowledgement), 0), + fixed_header: FixedHeader::new( + PacketType::with_default(ControlType::SubscribeAcknowledgement), + 0, + ), packet_identifier: PacketIdentifier(pkid), payload: SubackPacketPayload::new(subscribes), }; - pk.fixed_header.remaining_length = pk.encoded_variable_headers_length() + pk.payload.encoded_length(); + pk.fixed_header.remaining_length = + pk.encoded_variable_headers_length() + pk.payload.encoded_length(); pk } @@ -104,17 +108,21 @@ impl Packet for SubackPacket { self.packet_identifier.encoded_length() } - fn decode_packet(reader: &mut R, fixed_header: FixedHeader) -> Result> { + fn decode_packet( + reader: &mut R, + fixed_header: FixedHeader, + ) -> Result> { let packet_identifier: PacketIdentifier = PacketIdentifier::decode(reader)?; - let payload: SubackPacketPayload = - SubackPacketPayload::decode_with(reader, - Some(fixed_header.remaining_length - packet_identifier.encoded_length())) - .map_err(PacketError::PayloadError)?; + let payload: SubackPacketPayload = SubackPacketPayload::decode_with( + reader, + Some(fixed_header.remaining_length - packet_identifier.encoded_length()), + ) + .map_err(PacketError::PayloadError)?; Ok(SubackPacket { - fixed_header: fixed_header, - packet_identifier: packet_identifier, - payload: payload, - }) + fixed_header, + packet_identifier, + payload, + }) } } @@ -153,9 +161,10 @@ impl Decodable for SubackPacketPayload { type Err = SubackPacketPayloadError; type Cond = u32; - fn decode_with(reader: &mut R, - payload_len: Option) - -> Result { + fn decode_with( + reader: &mut R, + payload_len: Option, + ) -> Result { let payload_len = payload_len.expect("Must provide payload length"); let mut subs = Vec::new(); @@ -183,9 +192,9 @@ pub enum SubackPacketPayloadError { impl fmt::Display for SubackPacketPayloadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &SubackPacketPayloadError::IoError(ref err) => err.fmt(f), - &SubackPacketPayloadError::InvalidSubscribeReturnCode(code) => { + match *self { + SubackPacketPayloadError::IoError(ref err) => err.fmt(f), + SubackPacketPayloadError::InvalidSubscribeReturnCode(code) => { write!(f, "Invalid subscribe return code {}", code) } } @@ -193,17 +202,10 @@ impl fmt::Display for SubackPacketPayloadError { } impl Error for SubackPacketPayloadError { - fn description(&self) -> &str { - match self { - &SubackPacketPayloadError::IoError(ref err) => err.description(), - &SubackPacketPayloadError::InvalidSubscribeReturnCode(..) => "Invalid subscribe return code", - } - } - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - &SubackPacketPayloadError::IoError(ref err) => Some(err), - &SubackPacketPayloadError::InvalidSubscribeReturnCode(..) => None, + match *self { + SubackPacketPayloadError::IoError(ref err) => Some(err), + SubackPacketPayloadError::InvalidSubscribeReturnCode(..) => None, } } } diff --git a/src/packet/subscribe.rs b/src/packet/subscribe.rs index 5c99710..e8cb4c1 100644 --- a/src/packet/subscribe.rs +++ b/src/packet/subscribe.rs @@ -8,12 +8,12 @@ use std::string::FromUtf8Error; use byteorder::{ReadBytesExt, WriteBytesExt}; -use crate::{Decodable, Encodable, QualityOfService}; -use crate::control::{ControlType, FixedHeader, PacketType}; use crate::control::variable_header::PacketIdentifier; +use crate::control::{ControlType, FixedHeader, PacketType}; use crate::encodable::StringEncodeError; use crate::packet::{Packet, PacketError}; use crate::topic_filter::{TopicFilter, TopicFilterError}; +use crate::{Decodable, Encodable, QualityOfService}; /// `SUBSCRIBE` packet #[derive(Debug, Eq, PartialEq, Clone)] @@ -30,7 +30,8 @@ impl SubscribePacket { packet_identifier: PacketIdentifier(pkid), payload: SubscribePacketPayload::new(subscribes), }; - pk.fixed_header.remaining_length = pk.encoded_variable_headers_length() + pk.payload.encoded_length(); + pk.fixed_header.remaining_length = + pk.encoded_variable_headers_length() + pk.payload.encoded_length(); pk } @@ -68,18 +69,21 @@ impl Packet for SubscribePacket { self.packet_identifier.encoded_length() } - fn decode_packet(reader: &mut R, fixed_header: FixedHeader) -> Result> { + fn decode_packet( + reader: &mut R, + fixed_header: FixedHeader, + ) -> Result> { let packet_identifier: PacketIdentifier = PacketIdentifier::decode(reader)?; - let payload: SubscribePacketPayload = - SubscribePacketPayload::decode_with(reader, - Some(fixed_header.remaining_length - - packet_identifier.encoded_length())) - .map_err(PacketError::PayloadError)?; + let payload: SubscribePacketPayload = SubscribePacketPayload::decode_with( + reader, + Some(fixed_header.remaining_length - packet_identifier.encoded_length()), + ) + .map_err(PacketError::PayloadError)?; Ok(SubscribePacket { - fixed_header: fixed_header, - packet_identifier: packet_identifier, - payload: payload, - }) + fixed_header, + packet_identifier, + payload, + }) } } @@ -122,9 +126,10 @@ impl Decodable for SubscribePacketPayload { type Err = SubscribePacketPayloadError; type Cond = u32; - fn decode_with(reader: &mut R, - payload_len: Option) - -> Result { + fn decode_with( + reader: &mut R, + payload_len: Option, + ) -> Result { let mut payload_len = payload_len.expect("Must provide payload length"); let mut subs = Vec::new(); @@ -156,34 +161,26 @@ pub enum SubscribePacketPayloadError { impl fmt::Display for SubscribePacketPayloadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &SubscribePacketPayloadError::IoError(ref err) => err.fmt(f), - &SubscribePacketPayloadError::FromUtf8Error(ref err) => err.fmt(f), - &SubscribePacketPayloadError::StringEncodeError(ref err) => err.fmt(f), - &SubscribePacketPayloadError::InvalidQualityOfService => write!(f, "Invalid quality of service"), - &SubscribePacketPayloadError::TopicFilterError(ref err) => err.fmt(f), + match *self { + SubscribePacketPayloadError::IoError(ref err) => err.fmt(f), + SubscribePacketPayloadError::FromUtf8Error(ref err) => err.fmt(f), + SubscribePacketPayloadError::StringEncodeError(ref err) => err.fmt(f), + SubscribePacketPayloadError::InvalidQualityOfService => { + write!(f, "Invalid quality of service") + } + SubscribePacketPayloadError::TopicFilterError(ref err) => err.fmt(f), } } } impl Error for SubscribePacketPayloadError { - fn description(&self) -> &str { - match self { - &SubscribePacketPayloadError::IoError(ref err) => err.description(), - &SubscribePacketPayloadError::FromUtf8Error(ref err) => err.description(), - &SubscribePacketPayloadError::StringEncodeError(ref err) => err.description(), - &SubscribePacketPayloadError::InvalidQualityOfService => "Invalid quality of service", - &SubscribePacketPayloadError::TopicFilterError(ref err) => err.description(), - } - } - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - &SubscribePacketPayloadError::IoError(ref err) => Some(err), - &SubscribePacketPayloadError::FromUtf8Error(ref err) => Some(err), - &SubscribePacketPayloadError::StringEncodeError(ref err) => Some(err), - &SubscribePacketPayloadError::InvalidQualityOfService => None, - &SubscribePacketPayloadError::TopicFilterError(ref err) => Some(err), + match *self { + SubscribePacketPayloadError::IoError(ref err) => Some(err), + SubscribePacketPayloadError::FromUtf8Error(ref err) => Some(err), + SubscribePacketPayloadError::StringEncodeError(ref err) => Some(err), + SubscribePacketPayloadError::InvalidQualityOfService => None, + SubscribePacketPayloadError::TopicFilterError(ref err) => Some(err), } } } diff --git a/src/packet/unsuback.rs b/src/packet/unsuback.rs index 0b0b39b..3705d97 100644 --- a/src/packet/unsuback.rs +++ b/src/packet/unsuback.rs @@ -2,10 +2,10 @@ use std::io::{Read, Write}; -use crate::{Decodable, Encodable}; -use crate::control::{ControlType, FixedHeader, PacketType}; use crate::control::variable_header::PacketIdentifier; +use crate::control::{ControlType, FixedHeader, PacketType}; use crate::packet::{Packet, PacketError}; +use crate::{Decodable, Encodable}; /// `UNSUBACK` packet #[derive(Debug, Eq, PartialEq, Clone)] @@ -18,7 +18,10 @@ pub struct UnsubackPacket { impl UnsubackPacket { pub fn new(pkid: u16) -> UnsubackPacket { UnsubackPacket { - fixed_header: FixedHeader::new(PacketType::with_default(ControlType::UnsubscribeAcknowledgement), 2), + fixed_header: FixedHeader::new( + PacketType::with_default(ControlType::UnsubscribeAcknowledgement), + 2, + ), packet_identifier: PacketIdentifier(pkid), payload: (), } @@ -58,12 +61,15 @@ impl Packet for UnsubackPacket { self.packet_identifier.encoded_length() } - fn decode_packet(reader: &mut R, fixed_header: FixedHeader) -> Result> { + fn decode_packet( + reader: &mut R, + fixed_header: FixedHeader, + ) -> Result> { let packet_identifier: PacketIdentifier = PacketIdentifier::decode(reader)?; Ok(UnsubackPacket { - fixed_header: fixed_header, - packet_identifier: packet_identifier, - payload: (), - }) + fixed_header, + packet_identifier, + payload: (), + }) } } diff --git a/src/packet/unsubscribe.rs b/src/packet/unsubscribe.rs index 17dfbab..66110c1 100644 --- a/src/packet/unsubscribe.rs +++ b/src/packet/unsubscribe.rs @@ -6,12 +6,12 @@ use std::fmt; use std::io::{self, Read, Write}; use std::string::FromUtf8Error; -use crate::{Decodable, Encodable}; -use crate::control::{ControlType, FixedHeader, PacketType}; use crate::control::variable_header::PacketIdentifier; +use crate::control::{ControlType, FixedHeader, PacketType}; use crate::encodable::StringEncodeError; use crate::packet::{Packet, PacketError}; use crate::topic_filter::{TopicFilter, TopicFilterError}; +use crate::{Decodable, Encodable}; /// `UNSUBSCRIBE` packet #[derive(Debug, Eq, PartialEq, Clone)] @@ -28,7 +28,8 @@ impl UnsubscribePacket { packet_identifier: PacketIdentifier(pkid), payload: UnsubscribePacketPayload::new(subscribes), }; - pk.fixed_header.remaining_length = pk.encoded_variable_headers_length() + pk.payload.encoded_length(); + pk.fixed_header.remaining_length = + pk.encoded_variable_headers_length() + pk.payload.encoded_length(); pk } @@ -66,18 +67,21 @@ impl Packet for UnsubscribePacket { self.packet_identifier.encoded_length() } - fn decode_packet(reader: &mut R, fixed_header: FixedHeader) -> Result> { + fn decode_packet( + reader: &mut R, + fixed_header: FixedHeader, + ) -> Result> { let packet_identifier: PacketIdentifier = PacketIdentifier::decode(reader)?; - let payload: UnsubscribePacketPayload = - UnsubscribePacketPayload::decode_with(reader, - Some(fixed_header.remaining_length - - packet_identifier.encoded_length())) - .map_err(PacketError::PayloadError)?; + let payload: UnsubscribePacketPayload = UnsubscribePacketPayload::decode_with( + reader, + Some(fixed_header.remaining_length - packet_identifier.encoded_length()), + ) + .map_err(PacketError::PayloadError)?; Ok(UnsubscribePacket { - fixed_header: fixed_header, - packet_identifier: packet_identifier, - payload: payload, - }) + fixed_header, + packet_identifier, + payload, + }) } } @@ -118,9 +122,10 @@ impl Decodable for UnsubscribePacketPayload { type Err = UnsubscribePacketPayloadError; type Cond = u32; - fn decode_with(reader: &mut R, - payload_len: Option) - -> Result { + fn decode_with( + reader: &mut R, + payload_len: Option, + ) -> Result { let mut payload_len = payload_len.expect("Must provide payload length"); let mut subs = Vec::new(); @@ -144,31 +149,22 @@ pub enum UnsubscribePacketPayloadError { impl fmt::Display for UnsubscribePacketPayloadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &UnsubscribePacketPayloadError::IoError(ref err) => err.fmt(f), - &UnsubscribePacketPayloadError::FromUtf8Error(ref err) => err.fmt(f), - &UnsubscribePacketPayloadError::StringEncodeError(ref err) => err.fmt(f), - &UnsubscribePacketPayloadError::TopicFilterError(ref err) => err.fmt(f), + match *self { + UnsubscribePacketPayloadError::IoError(ref err) => err.fmt(f), + UnsubscribePacketPayloadError::FromUtf8Error(ref err) => err.fmt(f), + UnsubscribePacketPayloadError::StringEncodeError(ref err) => err.fmt(f), + UnsubscribePacketPayloadError::TopicFilterError(ref err) => err.fmt(f), } } } impl Error for UnsubscribePacketPayloadError { - fn description(&self) -> &str { - match self { - &UnsubscribePacketPayloadError::IoError(ref err) => err.description(), - &UnsubscribePacketPayloadError::FromUtf8Error(ref err) => err.description(), - &UnsubscribePacketPayloadError::StringEncodeError(ref err) => err.description(), - &UnsubscribePacketPayloadError::TopicFilterError(ref err) => err.description(), - } - } - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - &UnsubscribePacketPayloadError::IoError(ref err) => Some(err), - &UnsubscribePacketPayloadError::FromUtf8Error(ref err) => Some(err), - &UnsubscribePacketPayloadError::StringEncodeError(ref err) => Some(err), - &UnsubscribePacketPayloadError::TopicFilterError(ref err) => Some(err), + match *self { + UnsubscribePacketPayloadError::IoError(ref err) => Some(err), + UnsubscribePacketPayloadError::FromUtf8Error(ref err) => Some(err), + UnsubscribePacketPayloadError::StringEncodeError(ref err) => Some(err), + UnsubscribePacketPayloadError::TopicFilterError(ref err) => Some(err), } } } diff --git a/src/topic_filter.rs b/src/topic_filter.rs index 21de971..87ffdc7 100644 --- a/src/topic_filter.rs +++ b/src/topic_filter.rs @@ -4,17 +4,16 @@ use std::convert::Into; use std::error::Error; use std::fmt; use std::io::{Read, Write}; -use std::mem; use std::ops::Deref; use lazy_static::lazy_static; use regex::Regex; -use crate::{Decodable, Encodable}; use crate::encodable::StringEncodeError; use crate::topic_name::TopicNameRef; +use crate::{Decodable, Encodable}; -const VALIDATE_TOPIC_FILTER_REGEX: &'static str = r"^(([^+#]*|\+)(/([^+#]*|\+))*(/#)?|#)$"; +const VALIDATE_TOPIC_FILTER_REGEX: &str = r"^(([^+#]*|\+)(/([^+#]*|\+))*(/#)?|#)$"; lazy_static! { static ref TOPIC_FILTER_VALIDATOR: Regex = Regex::new(VALIDATE_TOPIC_FILTER_REGEX).unwrap(); @@ -52,6 +51,11 @@ impl TopicFilter { } /// Creates a new topic filter from string without validation + /// + /// # Safety + /// + /// Topic filters' syntax is defined in [MQTT specification](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718106). + /// Creating a filter from raw string may cause errors pub unsafe fn new_unchecked>(topic: S) -> TopicFilter { TopicFilter(topic.into()) } @@ -75,9 +79,12 @@ impl Decodable for TopicFilter { type Err = TopicFilterError; type Cond = (); - fn decode_with(reader: &mut R, _rest: Option<()>) -> Result { - let topic_filter: String = Decodable::decode(reader) - .map_err(TopicFilterError::StringEncodeError)?; + fn decode_with( + reader: &mut R, + _rest: Option<()>, + ) -> Result { + let topic_filter: String = + Decodable::decode(reader).map_err(TopicFilterError::StringEncodeError)?; TopicFilter::new(topic_filter) } } @@ -102,17 +109,23 @@ impl TopicFilterRef { if is_invalid_topic_filter(topic) { Err(TopicFilterError::InvalidTopicFilter(topic.to_owned())) } else { - Ok(unsafe { mem::transmute(topic) }) + Ok(unsafe { &*(topic as *const str as *const TopicFilterRef) }) } } /// Creates a new topic filter from string without validation + /// + /// # Safety + /// + /// Topic filters' syntax is defined in [MQTT specification](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718106). + /// Creating a filter from raw string may cause errors pub unsafe fn new_unchecked + ?Sized>(topic: &S) -> &TopicFilterRef { - mem::transmute(topic.as_ref()) + let topic = topic.as_ref(); + &*(topic as *const str as *const TopicFilterRef) } /// Get a matcher - pub fn get_matcher<'a>(&'a self) -> TopicFilterMatcher<'a> { + pub fn get_matcher(&self) -> TopicFilterMatcher<'_> { TopicFilterMatcher::new(&self.0) } } @@ -134,25 +147,20 @@ pub enum TopicFilterError { impl fmt::Display for TopicFilterError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &TopicFilterError::StringEncodeError(ref err) => err.fmt(f), - &TopicFilterError::InvalidTopicFilter(ref topic) => write!(f, "Invalid topic filter ({})", topic), + match *self { + TopicFilterError::StringEncodeError(ref err) => err.fmt(f), + TopicFilterError::InvalidTopicFilter(ref topic) => { + write!(f, "Invalid topic filter ({})", topic) + } } } } impl Error for TopicFilterError { - fn description(&self) -> &str { - match self { - &TopicFilterError::StringEncodeError(ref err) => err.description(), - &TopicFilterError::InvalidTopicFilter(..) => "Invalid topic filter", - } - } - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - &TopicFilterError::StringEncodeError(ref err) => Some(err), - &TopicFilterError::InvalidTopicFilter(..) => None, + match *self { + TopicFilterError::StringEncodeError(ref err) => Some(err), + TopicFilterError::InvalidTopicFilter(..) => None, } } } @@ -165,7 +173,9 @@ pub struct TopicFilterMatcher<'a> { impl<'a> TopicFilterMatcher<'a> { fn new(filter: &'a str) -> TopicFilterMatcher<'a> { - TopicFilterMatcher { topic_filter: filter } + TopicFilterMatcher { + topic_filter: filter, + } } /// Check if this filter can match the `topic_name` @@ -198,17 +208,15 @@ impl<'a> TopicFilterMatcher<'a> { loop { match (ft_itr.next(), tn_itr.next()) { - (Some(ft), Some(tn)) => { - match ft { - "#" => break, - "+" => {} - _ => { - if ft != tn { - return false; - } + (Some(ft), Some(tn)) => match ft { + "#" => break, + "+" => {} + _ => { + if ft != tn { + return false; } } - } + }, (Some(ft), None) => { if ft != "#" { return false; @@ -221,7 +229,7 @@ impl<'a> TopicFilterMatcher<'a> { } } - return true; + true } } diff --git a/src/topic_name.rs b/src/topic_name.rs index 4abd5cf..6123cfb 100644 --- a/src/topic_name.rs +++ b/src/topic_name.rs @@ -4,16 +4,15 @@ use std::convert::Into; use std::error::Error; use std::fmt; use std::io::{Read, Write}; -use std::mem; use std::ops::Deref; use lazy_static::lazy_static; use regex::Regex; -use crate::{Decodable, Encodable}; use crate::encodable::StringEncodeError; +use crate::{Decodable, Encodable}; -const TOPIC_NAME_VALIDATE_REGEX: &'static str = r"^[^#+]+$"; +const TOPIC_NAME_VALIDATE_REGEX: &str = r"^[^#+]+$"; lazy_static! { static ref TOPIC_NAME_VALIDATOR: Regex = Regex::new(TOPIC_NAME_VALIDATE_REGEX).unwrap(); @@ -21,7 +20,9 @@ lazy_static! { #[inline] fn is_invalid_topic_name(topic_name: &str) -> bool { - topic_name.is_empty() || topic_name.as_bytes().len() > 65535 || !TOPIC_NAME_VALIDATOR.is_match(&topic_name) + topic_name.is_empty() + || topic_name.as_bytes().len() > 65535 + || !TOPIC_NAME_VALIDATOR.is_match(&topic_name) } /// Topic name @@ -43,6 +44,11 @@ impl TopicName { } /// Creates a new topic name from string without validation + /// + /// # Safety + /// + /// Topic names' syntax is defined in [MQTT specification](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718106). + /// Creating a name from raw string may cause errors pub unsafe fn new_unchecked(topic_name: String) -> TopicName { TopicName(topic_name) } @@ -80,9 +86,12 @@ impl Decodable for TopicName { type Err = TopicNameError; type Cond = (); - fn decode_with(reader: &mut R, _rest: Option<()>) -> Result { - let topic_name: String = Decodable::decode(reader) - .map_err(TopicNameError::StringEncodeError)?; + fn decode_with( + reader: &mut R, + _rest: Option<()>, + ) -> Result { + let topic_name: String = + Decodable::decode(reader).map_err(TopicNameError::StringEncodeError)?; TopicName::new(topic_name) } } @@ -96,25 +105,20 @@ pub enum TopicNameError { impl fmt::Display for TopicNameError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &TopicNameError::StringEncodeError(ref err) => err.fmt(f), - &TopicNameError::InvalidTopicName(ref topic) => write!(f, "Invalid topic filter ({})", topic), + match *self { + TopicNameError::StringEncodeError(ref err) => err.fmt(f), + TopicNameError::InvalidTopicName(ref topic) => { + write!(f, "Invalid topic filter ({})", topic) + } } } } impl Error for TopicNameError { - fn description(&self) -> &str { - match self { - &TopicNameError::StringEncodeError(ref err) => err.description(), - &TopicNameError::InvalidTopicName(..) => "Invalid topic filter", - } - } - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - &TopicNameError::StringEncodeError(ref err) => Some(err), - &TopicNameError::InvalidTopicName(..) => None, + match *self { + TopicNameError::StringEncodeError(ref err) => Some(err), + TopicNameError::InvalidTopicName(..) => None, } } } @@ -131,13 +135,19 @@ impl TopicNameRef { if is_invalid_topic_name(&topic_name) { Err(TopicNameError::InvalidTopicName(topic_name.to_owned())) } else { - Ok(unsafe { mem::transmute(topic_name) }) + Ok(unsafe { &*(topic_name as *const str as *const TopicNameRef) }) } } /// Creates a new topic name from string without validation + /// + /// # Safety + /// + /// Topic names' syntax is defined in [MQTT specification](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718106). + /// Creating a name from raw string may cause errors pub unsafe fn new_unchecked + ?Sized>(topic_name: &S) -> &TopicNameRef { - mem::transmute(topic_name.as_ref()) + let topic_name = topic_name.as_ref(); + &*(topic_name as *const str as *const TopicNameRef) } /// Check if this topic name is only for server.