Skip to content

Commit

Permalink
Implement Error and Display for FromStrError and `parse::ParseE…
Browse files Browse the repository at this point in the history
…rror`
  • Loading branch information
abonander committed Aug 23, 2017
1 parent 7b8b6c4 commit 1031854
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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),
Expand Down
25 changes: 25 additions & 0 deletions src/parse.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use std::ascii::AsciiExt;
use std::error::Error;
use std::fmt;
use std::iter::Enumerate;
use std::str::Bytes;

Expand All @@ -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<Mime, ParseError> {
if s == "*/*" {
return Ok(::STAR_STAR);
Expand Down

0 comments on commit 1031854

Please sign in to comment.