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
parent
cc9f630dbc
commit
ff8316895a
19
src/mac.rs
19
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<Self, ParseError> {
|
||||
s.split(":")
|
||||
let split: Result<Vec<_>, _> = s.split(":")
|
||||
.map(|b| u8::from_str_radix(b, 16))
|
||||
.collect::<Result<Vec<u8>, _>>()
|
||||
.and_then(|parts| {
|
||||
.collect();
|
||||
match split {
|
||||
Ok(parts) => {
|
||||
let mut addr = [0u8; 6];
|
||||
if parts.len() == 6 {
|
||||
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] {
|
||||
|
|
Loading…
Reference in New Issue