1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
#![deny(missing_docs)]
extern crate charsets;
use std::ascii::AsciiExt;
use std::collections::HashMap;
use std::error::Error as ErrorTrait;
use std::fmt::{self, Display, Formatter};
use std::str::{FromStr, Utf8Error, from_utf8};
use std::string::FromUtf8Error;
pub use type_::*;
pub use tree::*;
pub use charsets::Charset;
mod utils;
#[derive(Debug, Eq, PartialEq)]
pub enum Error {
Invalid,
NotFound,
Utf8Error(Utf8Error)
}
impl ErrorTrait for Error {
fn description(&self) -> &str {
return "TODO"
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.description())
}
}
impl From<charsets::Error> for Error {
fn from(_: charsets::Error) -> Error {
Error::Invalid
}
}
impl From<FromUtf8Error> for Error {
fn from(err: FromUtf8Error) -> Error {
Error::Utf8Error(err.utf8_error())
}
}
pub type Result<T> = ::std::result::Result<T, Error>;
#[derive(Debug, Default, Eq, PartialEq)]
pub struct MediaType {
pub type_: Option<String>,
pub tree: Option<String>,
pub subtype: Option<String>,
pub suffix: Option<String>,
pub parameters: HashMap<String, String>
}
fn u<'a>(x: &'a Option<String>) -> Option<&'a str> {
x.as_ref().map(|x| &x[..])
}
impl MediaType {
pub fn new(type_: Option<&str>,
tree: Option<&str>,
subtype: Option<&str>,
suffix: Option<&str>) -> MediaType {
MediaType {
type_: type_.map(|x| x.to_string()),
tree: tree.map(|x| x.to_string()),
subtype: subtype.map(|x| x.to_string()),
suffix: suffix.map(|x| x.to_string()),
parameters: HashMap::new()
}
}
pub fn boundary(&self) -> Result<&str> {
let boundary = try!(self.parameters.get("boundary").ok_or(Error::NotFound));
if !utils::boundary(boundary) {
return Err(Error::Invalid);
}
Ok(&boundary[..])
}
pub fn charset(&self) -> Result<Charset> {
let charset = try!(self.parameters.get("charset").ok_or(Error::NotFound));
Ok(try!(charset.parse()))
}
pub fn eq_mime_portion(&self, other: &MediaType) -> bool {
self.type_ == other.type_
&& self.tree == other.tree
&& self.subtype == other.subtype
&& self.suffix == other.suffix
}
pub fn ne_mime_portion(&self, other: &MediaType) -> bool {
!self.eq_mime_portion(other)
}
pub fn is_image_type(&self) -> bool {
u(&self.type_) == IMAGE
}
pub fn is_audio_or_video_type(&self) -> bool {
u(&self.type_) == AUDIO
|| u(&self.type_) == VIDEO
|| MediaType::new(APPLICATION, STANDARDS, Some("ogg"), None).eq_mime_portion(self)
}
pub fn is_font_type(&self) -> bool {
self == &MediaType::new(APPLICATION, STANDARDS, Some("font-ttf"), None)
|| [
MediaType::new(APPLICATION, STANDARDS, Some("font-cff"), None),
MediaType::new(APPLICATION, STANDARDS, Some("font-off"), None),
MediaType::new(APPLICATION, STANDARDS, Some("font-sfnt"), None),
MediaType::new(APPLICATION, VENDOR, Some("ms-opentype"), None),
MediaType::new(APPLICATION, STANDARDS, Some("font-woff"), None),
MediaType::new(APPLICATION, VENDOR, Some("ms-fontobject"), None)
].iter().any(|x| x.eq_mime_portion(self))
}
pub fn is_zip_based_type(&self) -> bool {
u(&self.suffix) == Some("zip")
|| MediaType::new(APPLICATION, STANDARDS, Some("zip"), None).eq_mime_portion(self)
}
pub fn is_archive_type(&self) -> bool {
self == &MediaType::new(APPLICATION, STANDARDS, Some("x-rar-compressed"), None)
|| [
MediaType::new(APPLICATION, STANDARDS, Some("zip"), None),
MediaType::new(APPLICATION, STANDARDS, Some("x-gzip"), None)
].iter().any(|x| x.eq_mime_portion(self))
}
pub fn is_xml_type(&self) -> bool {
u(&self.suffix) == Some("xml")
|| [
MediaType::new(TEXT, STANDARDS, Some("xml"), None),
MediaType::new(APPLICATION, STANDARDS, Some("xml"), None)
].iter().any(|x| x.eq_mime_portion(self))
}
pub fn is_scriptable_mime_type(&self) -> bool {
[
MediaType::new(TEXT, STANDARDS, Some("html"), None),
MediaType::new(APPLICATION, STANDARDS, Some("pdf"), None)
].iter().any(|x| x.eq_mime_portion(self))
}
}
impl FromStr for MediaType {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
if s.is_empty() {
return Err(Error::Invalid)
}
let mut media_type: MediaType = Default::default();
let s = s.trim();
let mut parts = s.splitn(2, ';');
let mime_type_portion = try!(parts.next().ok_or(Error::Invalid));
let parameters_portion = parts.next();
let mut parts = mime_type_portion.splitn(2, '/');
media_type.type_ = Some(try!(parts.next().ok_or(Error::Invalid)).to_ascii_lowercase())
.and_then(parse_wildcard);
let subtype_portion = try!(parts.next().ok_or(Error::Invalid));
let suffixed_portion = if subtype_portion.contains('.') {
let mut parts = subtype_portion.splitn(2, '.');
media_type.tree = Some(parts.next().unwrap().to_ascii_lowercase());
parts.next().unwrap()
} else {
subtype_portion
};
media_type.subtype = Some(if suffixed_portion.contains('+') {
let mut parts = suffixed_portion.rsplitn(2, '+');
media_type.suffix = Some(parts.next().unwrap().to_ascii_lowercase());
parts.next().unwrap()
} else {
suffixed_portion
}.to_ascii_lowercase()).and_then(parse_wildcard);
if let Some(parameters_portion) = parameters_portion {
for (key, value) in try!(parameters_portion.split(';').map(|x| {
let mut parts = x.splitn(2, '=');
let key = try!(parts.next().map(|x| x.trim()).ok_or(Error::Invalid));
let value = try!(parts.next().map(utils::unquote_string).ok_or(Error::Invalid));
decode_param(key, value)
}).collect::<Result<Vec<(&str, String)>>>()) {
media_type.parameters.insert(key.to_ascii_lowercase(), value);
}
}
return Ok(media_type);
fn decode_param<'a>(key: &'a str, value: &'a str) -> Result<(&'a str, String)> {
Ok(if key.ends_with("*") {
(&key[0..key.len() -1],
try!(try!(String::from_utf8(utils::percent_decode(value.as_bytes())))
.splitn(3, '\'').nth(2)
.ok_or(Error::Invalid)).to_owned())
} else {
(key, value.to_owned())
})
}
fn parse_wildcard(s: String) -> Option<String> {
if s != "*" {
Some(s)
} else {
None
}
}
}
}
impl Display for MediaType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "{}/", self.type_.as_ref().map(|x| &x[..]).unwrap_or("*")));
if let Some(ref tree) = self.tree {
try!(write!(f, "{}.", tree));
}
try!(f.write_str(self.subtype.as_ref().map(|x| &x[..]).unwrap_or("*")));
if let Some(ref suffix) = self.suffix {
try!(write!(f, "+{}", suffix));
}
let mut items: Vec<(&String, &String)> = self.parameters.iter().collect();
items.sort_by(|&(ref first, _), &(ref second, _)| first.cmp(second));
for (ref key, ref value) in items {
if utils::token(&value) {
try!(write!(f, "; {}={}", key, value));
} else {
try!(write!(f, "; {}=\"{}\"", key, value));
}
};
Ok(())
}
}
pub mod type_ {
pub const TEXT: Option<&'static str> = Some("text");
pub const IMAGE: Option<&'static str> = Some("image");
pub const AUDIO: Option<&'static str> = Some("audio");
pub const VIDEO: Option<&'static str> = Some("video");
pub const APPLICATION: Option<&'static str> = Some("application");
pub const MULTIPART: Option<&'static str> = Some("multipart");
pub const MESSAGE: Option<&'static str> = Some("message");
}
pub mod tree {
pub const STANDARDS: Option<&'static str> = None;
pub const VENDOR: Option<&'static str> = Some("vnd");
pub const PERSONAL: Option<&'static str> = Some("prs");
pub const UNREGISTERED: Option<&'static str> = Some("x");
}