mac: Add ParseError enum

The `mac::ParseError` enumeration is intended to represent all of the
possible ways `MacAddress::from_string` could fail. For now, the only
known problem is an invalid hexadecimal integer found in one of the
octets, which causes a `ParseIntError`. The `ParseError` enum implements
the `Debug`, `Display`, and `Error` traits.
master
Dustin 2018-09-20 20:56:37 -05:00
parent e3e4c39f21
commit cc9f630dbc
1 changed files with 36 additions and 2 deletions

View File

@ -1,13 +1,46 @@
use std::error;
use std::fmt;
use std::num; use std::num;
#[derive(Debug)]
pub enum ParseError {
Value(num::ParseIntError),
}
impl From<num::ParseIntError> for ParseError {
fn from(e: num::ParseIntError) -> Self {
ParseError::Value(e)
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ParseError::Value(ref e) => e.fmt(f),
}
}
}
impl error::Error for ParseError {
fn cause(&self) -> Option<&error::Error> {
match *self {
ParseError::Value(ref e) => Some(e),
}
}
}
pub struct MacAddress { pub struct MacAddress {
addr: [u8; 6], addr: [u8; 6],
} }
impl MacAddress { impl MacAddress {
pub fn from_string(s: &str) -> Result<Self, num::ParseIntError> { pub fn from_string(s: &str) -> Result<Self, ParseError> {
s.split(":") s.split(":")
.map(|b| u8::from_str_radix(b, 16)) .map(|b| u8::from_str_radix(b, 16))
.collect::<Result<Vec<u8>, _>>() .collect::<Result<Vec<u8>, _>>()
@ -15,7 +48,8 @@ impl MacAddress {
let mut addr = [0u8; 6]; let mut addr = [0u8; 6];
addr.copy_from_slice(&parts[..6]); addr.copy_from_slice(&parts[..6]);
Ok(MacAddress { addr }) Ok(MacAddress { addr })
}) })
.map_err(ParseError::from)
} }
pub fn as_bytes(&self) -> &[u8; 6] { pub fn as_bytes(&self) -> &[u8; 6] {