diff --git a/src/mac.rs b/src/mac.rs index 88c68fb..b87ae88 100644 --- a/src/mac.rs +++ b/src/mac.rs @@ -6,6 +6,7 @@ use std::num; #[derive(Debug)] pub enum ParseError { Value(num::ParseIntError), + Format, } @@ -20,6 +21,7 @@ impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { 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> { match *self { ParseError::Value(ref e) => Some(e), + ParseError::Format => None, } } } @@ -41,15 +44,21 @@ pub struct MacAddress { impl MacAddress { pub fn from_string(s: &str) -> Result { - s.split(":") + let split: Result, _> = s.split(":") .map(|b| u8::from_str_radix(b, 16)) - .collect::, _>>() - .and_then(|parts| { + .collect(); + match split { + Ok(parts) => { let mut addr = [0u8; 6]; - addr.copy_from_slice(&parts[..6]); - Ok(MacAddress { addr }) - }) - .map_err(ParseError::from) + if parts.len() == 6 { + addr.copy_from_slice(&parts[..6]); + Ok(MacAddress { addr }) + } else { + Err(ParseError::Format) + } + }, + Err(e) => Err(ParseError::from(e)), + } } pub fn as_bytes(&self) -> &[u8; 6] {