Skip to content

Commit 1031854

Browse files
committed
Implement Error and Display for FromStrError and parse::ParseError
1 parent 7b8b6c4 commit 1031854

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/lib.rs

+13
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
extern crate unicase;
3333

3434
use std::cmp::Ordering;
35+
use std::error::Error;
3536
use std::fmt;
3637
use std::hash::{Hash, Hasher};
3738
use std::str::FromStr;
@@ -74,6 +75,18 @@ pub struct FromStrError {
7475
inner: parse::ParseError,
7576
}
7677

78+
impl Error for FromStrError {
79+
fn description(&self) -> &str {
80+
"an error occurred while parsing a MIME type"
81+
}
82+
}
83+
84+
impl fmt::Display for FromStrError {
85+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
86+
write!(f, "{}: {}", self.description(), self.inner)
87+
}
88+
}
89+
7790
#[derive(Clone)]
7891
enum Source {
7992
Atom(u8, &'static str),

src/parse.rs

+25
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
use std::ascii::AsciiExt;
2+
use std::error::Error;
3+
use std::fmt;
24
use std::iter::Enumerate;
35
use std::str::Bytes;
46

@@ -15,6 +17,29 @@ pub enum ParseError {
1517
},
1618
}
1719

20+
impl Error for ParseError {
21+
fn description(&self) -> &str {
22+
use self::ParseError::*;
23+
24+
match *self {
25+
MissingSlash => "a slash (/) was missing between the type and subtype",
26+
MissingEqual => "an equals sign (=) was missing between a parameter and its value",
27+
MissingQuote => "a quote (\") was missing from a parameter value",
28+
InvalidToken { .. } => "an invalid token was encountered",
29+
}
30+
}
31+
}
32+
33+
impl fmt::Display for ParseError {
34+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
35+
if let ParseError::InvalidToken { pos, byte } = *self {
36+
write!(f, "{}, {:X} at position {}", self.description(), byte, pos)
37+
} else {
38+
f.write_str(self.description())
39+
}
40+
}
41+
}
42+
1843
pub fn parse(s: &str) -> Result<Mime, ParseError> {
1944
if s == "*/*" {
2045
return Ok(::STAR_STAR);

0 commit comments

Comments
 (0)