From 6733f900364de401b80d872db7baaa1b683c442a Mon Sep 17 00:00:00 2001 From: Sunil Nimmagadda Date: Mon, 18 Nov 2024 22:54:37 +0530 Subject: Implement From trait from VRRPv2Error and use ? everywhere. --- src/vrrpv2.rs | 40 ++++++++++++++-------------------------- 1 file changed, 14 insertions(+), 26 deletions(-) diff --git a/src/vrrpv2.rs b/src/vrrpv2.rs index ee2c5f7..7ef30f3 100644 --- a/src/vrrpv2.rs +++ b/src/vrrpv2.rs @@ -35,7 +35,7 @@ pub struct VRRPv2 { pub ip_addrs: Vec, } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, PartialEq)] pub enum VRRPv2Error { InvalidAuthType, InvalidChecksum, @@ -56,7 +56,11 @@ impl std::fmt::Display for VRRPv2Error { } } -impl std::error::Error for VRRPv2Error {} +impl From for VRRPv2Error { + fn from(_err: std::io::Error) -> VRRPv2Error { + VRRPv2Error::ParseError + } +} #[derive(Debug, PartialEq)] pub enum VRRPv2AuthType { @@ -93,44 +97,28 @@ impl> BytesReader for Cursor { fn parse(bytes: &[u8]) -> Result { let mut rdr = Cursor::new(bytes); - let Ok(vertype) = rdr.read_u8() else { - return Err(VRRPv2Error::ParseError); - }; + let vertype = rdr.read_u8()?; if (vertype & 0xF) != 1 { return Err(VRRPv2Error::InvalidType); } if (vertype >> 4) != 2 { return Err(VRRPv2Error::InvalidVersion); } - let Ok(virtual_router_id) = rdr.read_u8() else { - return Err(VRRPv2Error::ParseError); - }; - let Ok(priority) = rdr.read_u8() else { - return Err(VRRPv2Error::ParseError); - }; - let Ok(count_ip_addrs) = rdr.read_u8() else { - return Err(VRRPv2Error::ParseError); - }; - let Ok(auth_type) = rdr.read_u8() else { - return Err(VRRPv2Error::ParseError); - }; + let virtual_router_id = rdr.read_u8()?; + let priority = rdr.read_u8()?; + let count_ip_addrs = rdr.read_u8()?; + let auth_type = rdr.read_u8()?; let auth_type = match auth_type { 0 => VRRPv2AuthType::VRRPv2AuthNoAuth, 1 => VRRPv2AuthType::VRRPv2AuthReserved1, 2 => VRRPv2AuthType::VRRPv2AuthReserved2, _ => return Err(VRRPv2Error::InvalidAuthType), }; - let Ok(advertisement_interval) = rdr.read_u8() else { - return Err(VRRPv2Error::ParseError); - }; - let Ok(checksum) = rdr.read_u16() else { - return Err(VRRPv2Error::ParseError); - }; + let advertisement_interval = rdr.read_u8()?; + let checksum = rdr.read_u16()?; let mut ip_addrs = Vec::with_capacity(count_ip_addrs as usize); for _i in 0..count_ip_addrs { - let Ok(b) = rdr.read_u32() else { - return Err(VRRPv2Error::ParseError); - }; + let b = rdr.read_u32()?; ip_addrs.push(Ipv4Addr::from(b)); } Ok(VRRPv2 { -- cgit v1.2.3