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
parent
e3e4c39f21
commit
cc9f630dbc
36
src/mac.rs
36
src/mac.rs
|
@ -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>, _>>()
|
||||||
|
@ -16,6 +49,7 @@ impl MacAddress {
|
||||||
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] {
|
||||||
|
|
Loading…
Reference in New Issue