diff options
| -rw-r--r-- | src/vrrpv2.rs | 54 | 
1 files changed, 27 insertions, 27 deletions
diff --git a/src/vrrpv2.rs b/src/vrrpv2.rs index 16bd74e..f8f1521 100644 --- a/src/vrrpv2.rs +++ b/src/vrrpv2.rs @@ -77,34 +77,7 @@ fn parse_auth_type(input: &[u8]) -> IResult<&[u8], VRRPv2AuthType> {      })(input)  } -// Nightly has a nicer array_chunks API to express it more succinctly. -// let mut chunks = bytes.array_chunks(2); -// let mut sum = chunks.map(u16::from_ne_bytes).map(|b| b as u32).sum::<u32>(); -// // handle the remainder -// if let Some([b]) = chunks.remainder() { -//     sum += *b as u32 -// } - -// Shadowing can be used to avoid `mut`... -// let sum =...; -// let sum = (sum & 0xffff) + (sum >> 16); -// let sum = (sum & 0xffff) + (sum >> 16); -// manually un-rolling while loop since it's needed atmost twice for an u32. -fn validate_checksum(bytes: &[u8]) -> bool { -    let mut sum: u32 = bytes.chunks(2).fold(0, |acc: u32, x| { -        acc + u32::from(u16::from_ne_bytes(x.try_into().unwrap())) -    }); -    while (sum >> 16) > 0 { -        sum = (sum & 0xffff) + (sum >> 16); -    } -    let checksum = !(sum as u16); -    checksum == 0 -} -  fn parse(input: &[u8]) -> IResult<&[u8], VRRPv2> { -    if !validate_checksum(input) { -        return Err(Err::Error(Error::new(input, ErrorKind::Alt))); -    }      let (input, (version, type_)) = parse_version_type(input)?;      let (input, virtual_router_id) = u8(input)?;      let (input, priority) = u8(input)?; @@ -130,7 +103,34 @@ fn parse(input: &[u8]) -> IResult<&[u8], VRRPv2> {      ))  } +// Nightly has a nicer array_chunks API to express it more succinctly. +// let mut chunks = bytes.array_chunks(2); +// let mut sum = chunks.map(u16::from_ne_bytes).map(|b| b as u32).sum::<u32>(); +// // handle the remainder +// if let Some([b]) = chunks.remainder() { +//     sum += *b as u32 +// } + +// Shadowing can be used to avoid `mut`... +// let sum =...; +// let sum = (sum & 0xffff) + (sum >> 16); +// let sum = (sum & 0xffff) + (sum >> 16); +// manually un-rolling while loop since it's needed atmost twice for an u32. +fn validate_checksum(bytes: &[u8]) -> bool { +    let mut sum: u32 = bytes.chunks(2).fold(0, |acc: u32, x| { +        acc + u32::from(u16::from_ne_bytes(x.try_into().unwrap())) +    }); +    while (sum >> 16) > 0 { +        sum = (sum & 0xffff) + (sum >> 16); +    } +    let checksum = !(sum as u16); +    checksum == 0 +} +  pub fn from_bytes(bytes: &[u8]) -> Result<VRRPv2, VRRPv2Error> { +    if !validate_checksum(bytes) { +        return Err(VRRPv2Error::VRRPv2ParseError); +    }      match parse(bytes) {          Ok((_, v)) => Ok(v),          Err(e) => Err(e.into()),  | 
