Skip to main content

mime/
lib.rs

1//! # Mime
2//!
3//! Mime is now Media Type, technically, but `Mime` is more immediately
4//! understandable, so the main type here is `Mime`.
5//!
6//! ## What is Mime?
7//!
8//! Example mime string: `text/plain`
9//!
10//! ```
11//! let plain_text: mime::Mime = "text/plain".parse().unwrap();
12//! assert_eq!(plain_text, mime::TEXT_PLAIN);
13//! ```
14//!
15//! ## Inspecting Mimes
16//!
17//! ```
18//! let mime = mime::TEXT_PLAIN;
19//! match (mime.type_(), mime.subtype()) {
20//!     (mime::TEXT, mime::PLAIN) => println!("plain text!"),
21//!     (mime::TEXT, _) => println!("structured text"),
22//!     _ => println!("not text"),
23//! }
24//! ```
25
26#![doc(html_root_url = "https://docs.rs/mime/0.3.17")]
27#![deny(warnings)]
28#![deny(missing_docs)]
29#![deny(missing_debug_implementations)]
30
31use std::cmp::Ordering;
32use std::error::Error;
33use std::fmt;
34use std::hash::{Hash, Hasher};
35use std::slice;
36use std::str::FromStr;
37
38mod parse;
39
40/// A parsed mime or media type.
41#[derive(Clone)]
42pub struct Mime {
43    source: Source,
44    slash: usize,
45    plus: Option<usize>,
46    params: ParamSource,
47}
48
49/// An iterator of parsed mime
50#[derive(Clone, Debug)]
51pub struct MimeIter<'a> {
52    pos: usize,
53    source: &'a str,
54}
55
56/// A section of a `Mime`.
57///
58/// For instance, for the Mime `image/svg+xml`, it contains 3 `Name`s,
59/// `image`, `svg`, and `xml`.
60///
61/// In most cases, `Name`s are compared ignoring case.
62#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
63pub struct Name<'a> {
64    // TODO: optimize with an Atom-like thing
65    // There a `const` Names, and so it is possible for the statis strings
66    // to havea different memory address. Additionally, when used in match
67    // statements, the strings are compared with a memcmp, possibly even
68    // if the address and length are the same.
69    //
70    // Being an enum with an Atom variant that is a usize (and without a
71    // string pointer and boolean) would allow for faster comparisons.
72    source: &'a str,
73    insensitive: bool,
74}
75
76/// An error when parsing a `Mime` from a string.
77#[derive(Debug)]
78pub struct FromStrError {
79    inner: parse::ParseError,
80}
81
82impl FromStrError {
83    fn s(&self) -> &str {
84        "mime parse error"
85    }
86}
87
88impl fmt::Display for FromStrError {
89    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90        write!(f, "{}: {}", self.s(), self.inner)
91    }
92}
93
94impl Error for FromStrError {
95    // Minimum Rust is 1.15, Error::description was still required then
96    #[allow(deprecated)]
97    fn description(&self) -> &str {
98        self.s()
99    }
100}
101
102#[derive(Clone)]
103enum Source {
104    Atom(u8, &'static str),
105    Dynamic(String),
106}
107
108impl Source {
109    fn as_ref(&self) -> &str {
110        match *self {
111            Source::Atom(_, s) => s,
112            Source::Dynamic(ref s) => s,
113        }
114    }
115}
116
117#[derive(Clone)]
118enum ParamSource {
119    Utf8(usize),
120    Custom(usize, Vec<(Indexed, Indexed)>),
121    None,
122}
123
124#[derive(Clone, Copy)]
125struct Indexed(usize, usize);
126
127impl Mime {
128    /// Get the top level media type for this `Mime`.
129    ///
130    /// # Example
131    ///
132    /// ```
133    /// let mime = mime::TEXT_PLAIN;
134    /// assert_eq!(mime.type_(), "text");
135    /// assert_eq!(mime.type_(), mime::TEXT);
136    /// ```
137    #[inline]
138    pub fn type_<'a>(&'a self) -> Name<'a> {
139        Name {
140            source: &self.source.as_ref()[..self.slash],
141            insensitive: true,
142        }
143    }
144
145    /// Get the subtype of this `Mime`.
146    ///
147    /// # Example
148    ///
149    /// ```
150    /// let mime = mime::TEXT_PLAIN;
151    /// assert_eq!(mime.subtype(), "plain");
152    /// assert_eq!(mime.subtype(), mime::PLAIN);
153    /// ```
154    #[inline]
155    pub fn subtype<'a>(&'a self) -> Name<'a> {
156        let end = self
157            .plus
158            .unwrap_or_else(|| return self.semicolon().unwrap_or(self.source.as_ref().len()));
159        Name {
160            source: &self.source.as_ref()[self.slash + 1..end],
161            insensitive: true,
162        }
163    }
164
165    /// Get an optional +suffix for this `Mime`.
166    ///
167    /// # Example
168    ///
169    /// ```
170    /// let svg = "image/svg+xml".parse::<mime::Mime>().unwrap();
171    /// assert_eq!(svg.suffix(), Some(mime::XML));
172    /// assert_eq!(svg.suffix().unwrap(), "xml");
173    ///
174    ///
175    /// assert!(mime::TEXT_PLAIN.suffix().is_none());
176    /// ```
177    #[inline]
178    pub fn suffix<'a>(&'a self) -> Option<Name<'a>> {
179        let end = self.semicolon().unwrap_or(self.source.as_ref().len());
180        self.plus.map(|idx| Name {
181            source: &self.source.as_ref()[idx + 1..end],
182            insensitive: true,
183        })
184    }
185
186    /// Look up a parameter by name.
187    ///
188    /// # Example
189    ///
190    /// ```
191    /// let mime = mime::TEXT_PLAIN_UTF_8;
192    /// assert_eq!(mime.get_param(mime::CHARSET), Some(mime::UTF_8));
193    /// assert_eq!(mime.get_param("charset").unwrap(), "utf-8");
194    /// assert!(mime.get_param("boundary").is_none());
195    ///
196    /// let mime = "multipart/form-data; boundary=ABCDEFG".parse::<mime::Mime>().unwrap();
197    /// assert_eq!(mime.get_param(mime::BOUNDARY).unwrap(), "ABCDEFG");
198    /// ```
199    pub fn get_param<'a, N>(&'a self, attr: N) -> Option<Name<'a>>
200    where
201        N: PartialEq<Name<'a>>,
202    {
203        self.params().find(|e| attr == e.0).map(|e| e.1)
204    }
205
206    /// Returns an iterator over the parameters.
207    #[inline]
208    pub fn params<'a>(&'a self) -> Params<'a> {
209        let inner = match self.params {
210            ParamSource::Utf8(_) => ParamsInner::Utf8,
211            ParamSource::Custom(_, ref params) => ParamsInner::Custom {
212                source: &self.source,
213                params: params.iter(),
214            },
215            ParamSource::None => ParamsInner::None,
216        };
217
218        Params(inner)
219    }
220
221    /// Return a `&str` of the Mime's ["essence"][essence].
222    ///
223    /// [essence]: https://mimesniff.spec.whatwg.org/#mime-type-essence
224    pub fn essence_str(&self) -> &str {
225        let end = self.semicolon().unwrap_or(self.source.as_ref().len());
226
227        &self.source.as_ref()[..end]
228    }
229
230    #[cfg(test)]
231    fn has_params(&self) -> bool {
232        match self.params {
233            ParamSource::None => false,
234            _ => true,
235        }
236    }
237
238    #[inline]
239    fn semicolon(&self) -> Option<usize> {
240        match self.params {
241            ParamSource::Utf8(i) | ParamSource::Custom(i, _) => Some(i),
242            ParamSource::None => None,
243        }
244    }
245
246    fn atom(&self) -> u8 {
247        match self.source {
248            Source::Atom(a, _) => a,
249            _ => 0,
250        }
251    }
252}
253
254// Mime ============
255
256fn eq_ascii(a: &str, b: &str) -> bool {
257    // str::eq_ignore_ascii_case didn't stabilize until Rust 1.23.
258    // So while our MSRV is 1.15, gotta import this trait.
259    #[allow(deprecated, unused)]
260    use std::ascii::AsciiExt;
261
262    a.eq_ignore_ascii_case(b)
263}
264
265fn mime_eq_str(mime: &Mime, s: &str) -> bool {
266    if mime.source.as_ref() == s {
267        return true;
268    }
269    if mime.semicolon().is_none() {
270        return eq_ascii(mime.source.as_ref(), s);
271    }
272
273    // Parse before comparing parameters, so arbitrary strings cannot cause
274    // invalid UTF-8 slicing and quoted values use the same rules as Mime.
275    match s.parse::<Mime>() {
276        Ok(other) => mime == &other,
277        Err(_) => false,
278    }
279}
280
281impl PartialEq for Mime {
282    #[inline]
283    fn eq(&self, other: &Mime) -> bool {
284        match (self.atom(), other.atom()) {
285            (0, _) | (_, 0) => {
286                self.essence_str() == other.essence_str() && self.params().eq(other.params())
287            }
288            (a, b) => a == b,
289        }
290    }
291}
292
293impl Eq for Mime {}
294
295impl PartialOrd for Mime {
296    fn partial_cmp(&self, other: &Mime) -> Option<Ordering> {
297        Some(self.cmp(other))
298    }
299}
300
301impl Ord for Mime {
302    fn cmp(&self, other: &Mime) -> Ordering {
303        match self.essence_str().cmp(other.essence_str()) {
304            Ordering::Equal => self.params().cmp(other.params()),
305            ordering => ordering,
306        }
307    }
308}
309
310impl Hash for Mime {
311    fn hash<T: Hasher>(&self, hasher: &mut T) {
312        self.essence_str().hash(hasher);
313        let mut count = 0usize;
314        for param in self.params() {
315            param.hash(hasher);
316            count += 1;
317        }
318        count.hash(hasher);
319    }
320}
321
322impl<'a> PartialEq<&'a str> for Mime {
323    #[inline]
324    fn eq(&self, s: &&'a str) -> bool {
325        mime_eq_str(self, *s)
326    }
327}
328
329impl<'a> PartialEq<Mime> for &'a str {
330    #[inline]
331    fn eq(&self, mime: &Mime) -> bool {
332        mime_eq_str(mime, *self)
333    }
334}
335
336impl FromStr for Mime {
337    type Err = FromStrError;
338
339    fn from_str(s: &str) -> Result<Mime, Self::Err> {
340        parse::parse(s).map_err(|e| FromStrError { inner: e })
341    }
342}
343
344impl AsRef<str> for Mime {
345    #[inline]
346    fn as_ref(&self) -> &str {
347        self.source.as_ref()
348    }
349}
350
351impl fmt::Debug for Mime {
352    #[inline]
353    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
354        fmt::Debug::fmt(self.source.as_ref(), f)
355    }
356}
357
358impl fmt::Display for Mime {
359    #[inline]
360    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
361        fmt::Display::fmt(self.source.as_ref(), f)
362    }
363}
364
365// Name ============
366
367fn name_eq_str(name: &Name, s: &str) -> bool {
368    if name.insensitive {
369        eq_ascii(name.source, s)
370    } else {
371        name.source == s
372    }
373}
374
375impl<'a> Name<'a> {
376    /// Get the value of this `Name` as a string.
377    ///
378    /// Note that the borrow is not tied to `&self` but the `'a` lifetime, allowing the
379    /// string to outlive `Name`. Alternately, there is an `impl<'a> From<Name<'a>> for &'a str`
380    /// which isn't rendered by Rustdoc, that can be accessed using `str::from(name)` or `name.into()`.
381    pub fn as_str(&self) -> &'a str {
382        self.source
383    }
384}
385
386impl<'a, 'b> PartialEq<&'b str> for Name<'a> {
387    #[inline]
388    fn eq(&self, other: &&'b str) -> bool {
389        name_eq_str(self, *other)
390    }
391}
392
393impl<'a, 'b> PartialEq<Name<'a>> for &'b str {
394    #[inline]
395    fn eq(&self, other: &Name<'a>) -> bool {
396        name_eq_str(other, *self)
397    }
398}
399
400impl<'a> AsRef<str> for Name<'a> {
401    #[inline]
402    fn as_ref(&self) -> &str {
403        self.source
404    }
405}
406
407impl<'a> From<Name<'a>> for &'a str {
408    #[inline]
409    fn from(name: Name<'a>) -> &'a str {
410        name.source
411    }
412}
413
414impl<'a> fmt::Debug for Name<'a> {
415    #[inline]
416    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
417        fmt::Debug::fmt(self.source, f)
418    }
419}
420
421impl<'a> fmt::Display for Name<'a> {
422    #[inline]
423    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
424        fmt::Display::fmt(self.source, f)
425    }
426}
427
428// Params ===================
429
430enum ParamsInner<'a> {
431    Utf8,
432    Custom {
433        source: &'a Source,
434        params: slice::Iter<'a, (Indexed, Indexed)>,
435    },
436    None,
437}
438
439/// An iterator over the parameters of a MIME.
440pub struct Params<'a>(ParamsInner<'a>);
441
442impl<'a> fmt::Debug for Params<'a> {
443    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
444        fmt.debug_struct("Params").finish()
445    }
446}
447
448impl<'a> Iterator for Params<'a> {
449    type Item = (Name<'a>, Name<'a>);
450
451    #[inline]
452    fn next(&mut self) -> Option<(Name<'a>, Name<'a>)> {
453        match self.0 {
454            ParamsInner::Utf8 => {
455                let value = (CHARSET, UTF_8);
456                self.0 = ParamsInner::None;
457                Some(value)
458            }
459            ParamsInner::Custom {
460                source,
461                ref mut params,
462            } => params.next().map(|&(name, value)| {
463                let name = Name {
464                    source: &source.as_ref()[name.0..name.1],
465                    insensitive: true,
466                };
467                let value = Name {
468                    source: &source.as_ref()[value.0..value.1],
469                    insensitive: name == CHARSET,
470                };
471                (name, value)
472            }),
473            ParamsInner::None => None,
474        }
475    }
476
477    #[inline]
478    fn size_hint(&self) -> (usize, Option<usize>) {
479        match self.0 {
480            ParamsInner::Utf8 => (1, Some(1)),
481            ParamsInner::Custom { ref params, .. } => params.size_hint(),
482            ParamsInner::None => (0, Some(0)),
483        }
484    }
485}
486
487macro_rules! names {
488    ($($id:ident, $e:expr;)*) => (
489        $(
490        #[doc = $e]
491        pub const $id: Name<'static> = Name {
492            source: $e,
493            insensitive: true,
494        };
495        )*
496
497        #[test]
498        fn test_names_macro_consts() {
499            #[allow(unused, deprecated)]
500            use std::ascii::AsciiExt;
501            $(
502            assert_eq!($id.source.to_ascii_lowercase(), $id.source);
503            )*
504        }
505    )
506}
507
508names! {
509    STAR, "*";
510
511    TEXT, "text";
512    IMAGE, "image";
513    AUDIO, "audio";
514    VIDEO, "video";
515    APPLICATION, "application";
516    MULTIPART, "multipart";
517    MESSAGE, "message";
518    MODEL, "model";
519    FONT, "font";
520
521    // common text/ *
522    PLAIN, "plain";
523    HTML, "html";
524    XML, "xml";
525    JAVASCRIPT, "javascript";
526    CSS, "css";
527    CSV, "csv";
528    EVENT_STREAM, "event-stream";
529    VCARD, "vcard";
530
531    // common application/*
532    JSON, "json";
533    WWW_FORM_URLENCODED, "x-www-form-urlencoded";
534    MSGPACK, "msgpack";
535    OCTET_STREAM, "octet-stream";
536    PDF, "pdf";
537
538    // common font/*
539    WOFF, "woff";
540    WOFF2, "woff2";
541
542    // multipart/*
543    FORM_DATA, "form-data";
544
545    // common image/*
546    BMP, "bmp";
547    GIF, "gif";
548    JPEG, "jpeg";
549    PNG, "png";
550    SVG, "svg";
551
552    // audio/*
553    BASIC, "basic";
554    MPEG, "mpeg";
555    MP4, "mp4";
556    OGG, "ogg";
557
558    // parameters
559    CHARSET, "charset";
560    BOUNDARY, "boundary";
561    UTF_8, "utf-8";
562}
563
564macro_rules! mimes {
565    ($($id:ident, $($piece:expr),*;)*) => (
566        #[allow(non_camel_case_types)]
567        enum __Atoms {
568            __Dynamic,
569        $(
570            $id,
571        )*
572        }
573
574        $(
575            mime_constant! {
576                $id, $($piece),*
577            }
578        )*
579
580        #[test]
581        fn test_mimes_macro_consts() {
582            let _ = [
583            $(
584            mime_constant_test! {
585                $id, $($piece),*
586            }
587            ),*
588            ].iter().enumerate().map(|(pos, &atom)| {
589                assert_eq!(pos + 1, atom as usize, "atom {} in position {}", atom, pos + 1);
590            }).collect::<Vec<()>>();
591        }
592    )
593}
594
595macro_rules! mime_constant {
596    ($id:ident, $src:expr, $slash:expr) => (
597        mime_constant!($id, $src, $slash, None);
598    );
599    ($id:ident, $src:expr, $slash:expr, $plus:expr) => (
600        mime_constant!(FULL $id, $src, $slash, $plus, ParamSource::None);
601    );
602
603    ($id:ident, $src:expr, $slash:expr, $plus:expr, $params:expr) => (
604        mime_constant!(FULL $id, $src, $slash, $plus, ParamSource::Utf8($params));
605    );
606
607
608    (FULL $id:ident, $src:expr, $slash:expr, $plus:expr, $params:expr) => (
609        #[doc = "`"]
610        #[doc = $src]
611        #[doc = "`"]
612        pub const $id: Mime = Mime {
613            source: Source::Atom(__Atoms::$id as u8, $src),
614            slash: $slash,
615            plus: $plus,
616            params: $params,
617        };
618    )
619}
620
621#[cfg(test)]
622macro_rules! mime_constant_test {
623    ($id:ident, $src:expr, $slash:expr) => (
624        mime_constant_test!($id, $src, $slash, None)
625    );
626    ($id:ident, $src:expr, $slash:expr, $plus:expr) => (
627        mime_constant_test!(FULL $id, $src, $slash, $plus, ParamSource::None)
628    );
629
630    ($id:ident, $src:expr, $slash:expr, $plus:expr, $params:expr) => (
631        mime_constant_test!(FULL $id, $src, $slash, $plus, ParamSource::Utf8($params))
632    );
633
634    (FULL $id:ident, $src:expr, $slash:expr, $plus:expr, $params:expr) => ({
635        let __mime = $id;
636        let __slash = __mime.as_ref().as_bytes()[$slash];
637        assert_eq!(__slash, b'/', "{:?} has {:?} at slash position {:?}", __mime, __slash as char, $slash);
638        if let Some(plus) = __mime.plus {
639            let __c = __mime.as_ref().as_bytes()[plus];
640            assert_eq!(__c, b'+', "{:?} has {:?} at plus position {:?}", __mime, __c as char, plus);
641        } else {
642            assert!(!__mime.as_ref().as_bytes().contains(&b'+'), "{:?} forgot plus", __mime);
643        }
644        if let ParamSource::Utf8(semicolon) = __mime.params {
645            assert_eq!(__mime.as_ref().as_bytes()[semicolon], b';');
646            assert_eq!(&__mime.as_ref()[semicolon..], "; charset=utf-8");
647        } else if let ParamSource::None = __mime.params {
648            assert!(!__mime.as_ref().as_bytes().contains(&b';'));
649        } else {
650            unreachable!();
651        }
652        __mime.atom()
653    })
654}
655
656mimes! {
657    STAR_STAR, "*/*", 1;
658
659    TEXT_STAR, "text/*", 4;
660    TEXT_PLAIN, "text/plain", 4;
661    TEXT_PLAIN_UTF_8, "text/plain; charset=utf-8", 4, None, 10;
662    TEXT_HTML, "text/html", 4;
663    TEXT_HTML_UTF_8, "text/html; charset=utf-8", 4, None, 9;
664    TEXT_CSS, "text/css", 4;
665    TEXT_CSS_UTF_8, "text/css; charset=utf-8", 4, None, 8;
666    TEXT_JAVASCRIPT, "text/javascript", 4;
667    TEXT_XML, "text/xml", 4;
668    TEXT_EVENT_STREAM, "text/event-stream", 4;
669    TEXT_CSV, "text/csv", 4;
670    TEXT_CSV_UTF_8, "text/csv; charset=utf-8", 4, None, 8;
671    TEXT_TAB_SEPARATED_VALUES, "text/tab-separated-values", 4;
672    TEXT_TAB_SEPARATED_VALUES_UTF_8, "text/tab-separated-values; charset=utf-8", 4, None, 25;
673    TEXT_VCARD, "text/vcard", 4;
674
675    IMAGE_STAR, "image/*", 5;
676    IMAGE_JPEG, "image/jpeg", 5;
677    IMAGE_GIF, "image/gif", 5;
678    IMAGE_PNG, "image/png", 5;
679    IMAGE_BMP, "image/bmp", 5;
680    IMAGE_SVG, "image/svg+xml", 5, Some(9);
681
682    FONT_WOFF, "font/woff", 4;
683    FONT_WOFF2, "font/woff2", 4;
684
685    APPLICATION_JSON, "application/json", 11;
686    APPLICATION_JAVASCRIPT, "application/javascript", 11;
687    APPLICATION_JAVASCRIPT_UTF_8, "application/javascript; charset=utf-8", 11, None, 22;
688    APPLICATION_WWW_FORM_URLENCODED, "application/x-www-form-urlencoded", 11;
689    APPLICATION_OCTET_STREAM, "application/octet-stream", 11;
690    APPLICATION_MSGPACK, "application/msgpack", 11;
691    APPLICATION_PDF, "application/pdf", 11;
692
693    MULTIPART_FORM_DATA, "multipart/form-data", 9;
694}
695
696#[deprecated(since = "0.3.1", note = "please use `TEXT_JAVASCRIPT` instead")]
697#[doc(hidden)]
698pub const TEXT_JAVSCRIPT: Mime = TEXT_JAVASCRIPT;
699
700#[cfg(test)]
701mod tests {
702    use super::*;
703    use std::str::FromStr;
704
705    #[test]
706    fn test_type_() {
707        assert_eq!(TEXT_PLAIN.type_(), TEXT);
708    }
709
710    #[test]
711    fn test_subtype() {
712        assert_eq!(TEXT_PLAIN.subtype(), PLAIN);
713        assert_eq!(TEXT_PLAIN_UTF_8.subtype(), PLAIN);
714        let mime = Mime::from_str("text/html+xml").unwrap();
715        assert_eq!(mime.subtype(), HTML);
716    }
717
718    #[test]
719    fn test_matching() {
720        match (TEXT_PLAIN.type_(), TEXT_PLAIN.subtype()) {
721            (TEXT, PLAIN) => (),
722            _ => unreachable!(),
723        }
724    }
725
726    #[test]
727    fn test_suffix() {
728        assert_eq!(TEXT_PLAIN.suffix(), None);
729        let mime = Mime::from_str("text/html+xml").unwrap();
730        assert_eq!(mime.suffix(), Some(XML));
731    }
732
733    #[test]
734    fn test_mime_fmt() {
735        let mime = TEXT_PLAIN;
736        assert_eq!(mime.to_string(), "text/plain");
737        let mime = TEXT_PLAIN_UTF_8;
738        assert_eq!(mime.to_string(), "text/plain; charset=utf-8");
739    }
740
741    #[test]
742    fn test_mime_from_str() {
743        assert_eq!(Mime::from_str("text/plain").unwrap(), TEXT_PLAIN);
744        assert_eq!(Mime::from_str("TEXT/PLAIN").unwrap(), TEXT_PLAIN);
745        assert_eq!(
746            Mime::from_str("text/plain;charset=utf-8").unwrap(),
747            TEXT_PLAIN_UTF_8
748        );
749        assert_eq!(
750            Mime::from_str("text/plain;charset=\"utf-8\"").unwrap(),
751            TEXT_PLAIN_UTF_8
752        );
753
754        // spaces
755        assert_eq!(
756            Mime::from_str("text/plain; charset=utf-8").unwrap(),
757            TEXT_PLAIN_UTF_8
758        );
759
760        // quotes + semi colon
761        Mime::from_str("text/plain;charset=\"utf-8\"; foo=bar").unwrap();
762        Mime::from_str("text/plain;charset=\"utf-8\" ; foo=bar").unwrap();
763
764        let upper = Mime::from_str("TEXT/PLAIN").unwrap();
765        assert_eq!(upper, TEXT_PLAIN);
766        assert_eq!(upper.type_(), TEXT);
767        assert_eq!(upper.subtype(), PLAIN);
768
769        let extended = Mime::from_str("TEXT/PLAIN; CHARSET=UTF-8; FOO=BAR").unwrap();
770        assert_eq!(extended, "text/plain; charset=utf-8; foo=BAR");
771        assert_eq!(extended.get_param("charset").unwrap(), "utf-8");
772        assert_eq!(extended.get_param("foo").unwrap(), "BAR");
773
774        Mime::from_str("multipart/form-data; boundary=--------foobar").unwrap();
775
776        // stars
777        assert_eq!("*/*".parse::<Mime>().unwrap(), STAR_STAR);
778        assert_eq!("image/*".parse::<Mime>().unwrap(), "image/*");
779        assert_eq!(
780            "text/*; charset=utf-8".parse::<Mime>().unwrap(),
781            "text/*; charset=utf-8"
782        );
783
784        // parse errors
785        Mime::from_str("f o o / bar").unwrap_err();
786        Mime::from_str("text\n/plain").unwrap_err();
787        Mime::from_str("text\r/plain").unwrap_err();
788        Mime::from_str("text/\r\nplain").unwrap_err();
789        Mime::from_str("text/plain;\r\ncharset=utf-8").unwrap_err();
790        Mime::from_str("text/plain; charset=\r\nutf-8").unwrap_err();
791        Mime::from_str("text/plain; charset=\"\r\nutf-8\"").unwrap_err();
792    }
793
794    #[test]
795    fn test_mime_from_str_empty_parameter_list() {
796        static CASES: &'static [&'static str] = &[
797            "text/event-stream;",
798            "text/event-stream; ",
799            "text/event-stream;       ",
800        ];
801
802        for case in CASES {
803            let mime = Mime::from_str(case).expect(case);
804            assert_eq!(mime, TEXT_EVENT_STREAM, "case = {:?}", case);
805            assert_eq!(mime.type_(), TEXT, "case = {:?}", case);
806            assert_eq!(mime.subtype(), EVENT_STREAM, "case = {:?}", case);
807            assert!(!mime.has_params(), "case = {:?}", case);
808        }
809    }
810
811    #[test]
812    fn test_case_sensitive_values() {
813        let mime = Mime::from_str("multipart/form-data; charset=BASE64; boundary=ABCDEFG").unwrap();
814        assert_eq!(mime.get_param(CHARSET).unwrap(), "bAsE64");
815        assert_eq!(mime.get_param(BOUNDARY).unwrap(), "ABCDEFG");
816        assert_ne!(mime.get_param(BOUNDARY).unwrap(), "abcdefg");
817    }
818
819    #[test]
820    fn test_get_param() {
821        assert_eq!(TEXT_PLAIN.get_param("charset"), None);
822        assert_eq!(TEXT_PLAIN.get_param("baz"), None);
823
824        assert_eq!(TEXT_PLAIN_UTF_8.get_param("charset"), Some(UTF_8));
825        assert_eq!(TEXT_PLAIN_UTF_8.get_param("baz"), None);
826
827        let mime = Mime::from_str("text/plain; charset=utf-8; foo=bar").unwrap();
828        assert_eq!(mime.get_param(CHARSET).unwrap(), "utf-8");
829        assert_eq!(mime.get_param("foo").unwrap(), "bar");
830        assert_eq!(mime.get_param("baz"), None);
831
832        let mime = Mime::from_str("text/plain;charset=\"utf-8\"").unwrap();
833        assert_eq!(mime.get_param(CHARSET), Some(UTF_8));
834    }
835
836    #[test]
837    fn test_name_eq() {
838        assert_eq!(TEXT, TEXT);
839        assert_eq!(TEXT, "text");
840        assert_eq!("text", TEXT);
841        assert_eq!(TEXT, "TEXT");
842
843        let param = Name {
844            source: "ABC",
845            insensitive: false,
846        };
847
848        assert_eq!(param, param);
849        assert_eq!(param, "ABC");
850        assert_eq!("ABC", param);
851        assert_ne!(param, "abc");
852        assert_ne!("abc", param);
853    }
854
855    #[test]
856    fn test_essence_str() {
857        assert_eq!(TEXT_PLAIN.essence_str(), "text/plain");
858        assert_eq!(TEXT_PLAIN_UTF_8.essence_str(), "text/plain");
859        assert_eq!(IMAGE_SVG.essence_str(), "image/svg+xml");
860    }
861}