From cc9f630dbc633689cf7b5ba30b816c8dc5d82a1a Mon Sep 17 00:00:00 2001 From: "Dustin C. Hatch" Date: Thu, 20 Sep 2018 20:56:37 -0500 Subject: [PATCH] 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. --- src/mac.rs | 38 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/src/mac.rs b/src/mac.rs index 7ce214d..88c68fb 100644 --- a/src/mac.rs +++ b/src/mac.rs @@ -1,13 +1,46 @@ +use std::error; +use std::fmt; use std::num; +#[derive(Debug)] +pub enum ParseError { + Value(num::ParseIntError), +} + + +impl From 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 { addr: [u8; 6], } impl MacAddress { - pub fn from_string(s: &str) -> Result { + pub fn from_string(s: &str) -> Result { s.split(":") .map(|b| u8::from_str_radix(b, 16)) .collect::, _>>() @@ -15,7 +48,8 @@ impl MacAddress { let mut addr = [0u8; 6]; addr.copy_from_slice(&parts[..6]); Ok(MacAddress { addr }) - }) + }) + .map_err(ParseError::from) } pub fn as_bytes(&self) -> &[u8; 6] {