mac: Handle improperly-formatted addresses

This commit introduces a new variant to the `ParseError` enumeration,
`ParseError::Format`. This error is returned by
`MacAddress::from_string()` when the input string is not correctly
formatted.
master
Dustin 2018-09-29 11:33:14 -05:00
parent cc9f630dbc
commit ff8316895a
1 changed files with 16 additions and 7 deletions

View File

@ -6,6 +6,7 @@ use std::num;
#[derive(Debug)] #[derive(Debug)]
pub enum ParseError { pub enum ParseError {
Value(num::ParseIntError), Value(num::ParseIntError),
Format,
} }
@ -20,6 +21,7 @@ impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { match *self {
ParseError::Value(ref e) => e.fmt(f), ParseError::Value(ref e) => e.fmt(f),
ParseError::Format => write!(f, "Invalid MAC address format"),
} }
} }
} }
@ -29,6 +31,7 @@ impl error::Error for ParseError {
fn cause(&self) -> Option<&error::Error> { fn cause(&self) -> Option<&error::Error> {
match *self { match *self {
ParseError::Value(ref e) => Some(e), ParseError::Value(ref e) => Some(e),
ParseError::Format => None,
} }
} }
} }
@ -41,15 +44,21 @@ pub struct MacAddress {
impl MacAddress { impl MacAddress {
pub fn from_string(s: &str) -> Result<Self, ParseError> { pub fn from_string(s: &str) -> Result<Self, ParseError> {
s.split(":") let split: Result<Vec<_>, _> = s.split(":")
.map(|b| u8::from_str_radix(b, 16)) .map(|b| u8::from_str_radix(b, 16))
.collect::<Result<Vec<u8>, _>>() .collect();
.and_then(|parts| { match split {
Ok(parts) => {
let mut addr = [0u8; 6]; let mut addr = [0u8; 6];
addr.copy_from_slice(&parts[..6]); if parts.len() == 6 {
Ok(MacAddress { addr }) addr.copy_from_slice(&parts[..6]);
}) Ok(MacAddress { addr })
.map_err(ParseError::from) } else {
Err(ParseError::Format)
}
},
Err(e) => Err(ParseError::from(e)),
}
} }
pub fn as_bytes(&self) -> &[u8; 6] { pub fn as_bytes(&self) -> &[u8; 6] {