diff --git a/src/lib.rs b/src/lib.rs index f86350b9..f959b67d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,6 +32,7 @@ extern crate unicase; use std::cmp::Ordering; +use std::error::Error; use std::fmt; use std::hash::{Hash, Hasher}; use std::str::FromStr; @@ -74,6 +75,18 @@ pub struct FromStrError { inner: parse::ParseError, } +impl Error for FromStrError { + fn description(&self) -> &str { + "an error occurred while parsing a MIME type" + } +} + +impl fmt::Display for FromStrError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}: {}", self.description(), self.inner) + } +} + #[derive(Clone)] enum Source { Atom(u8, &'static str), diff --git a/src/parse.rs b/src/parse.rs index 4f7071b2..f301bacb 100644 --- a/src/parse.rs +++ b/src/parse.rs @@ -1,4 +1,6 @@ use std::ascii::AsciiExt; +use std::error::Error; +use std::fmt; use std::iter::Enumerate; use std::str::Bytes; @@ -15,6 +17,29 @@ pub enum ParseError { }, } +impl Error for ParseError { + fn description(&self) -> &str { + use self::ParseError::*; + + match *self { + MissingSlash => "a slash (/) was missing between the type and subtype", + MissingEqual => "an equals sign (=) was missing between a parameter and its value", + MissingQuote => "a quote (\") was missing from a parameter value", + InvalidToken { .. } => "an invalid token was encountered", + } + } +} + +impl fmt::Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if let ParseError::InvalidToken { pos, byte } = *self { + write!(f, "{}, {:X} at position {}", self.description(), byte, pos) + } else { + f.write_str(self.description()) + } + } +} + pub fn parse(s: &str) -> Result { if s == "*/*" { return Ok(::STAR_STAR);