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
use mime::Mime;
use serde::{Serialize, Serializer};
use std::fmt;
use std::str::FromStr;
use thiserror::Error;

/// See [IETF RFC 7231](https://tools.ietf.org/html/rfc7231#section-5.3.2).
pub type MediaRange = Mime;

/// See [IETF RFC 2046](https://tools.ietf.org/html/rfc2046).
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct MediaType(MediaRange);
impl MediaType {
    pub const APPLICATION_OCTET_STREAM: Self = Self(mime::APPLICATION_OCTET_STREAM);

    pub fn from_media_range(media_range: MediaRange) -> Option<MediaType> {
        if media_range.type_() == "*" || media_range.subtype() == "*" {
            None
        } else {
            Some(MediaType(media_range))
        }
    }

    pub fn is_within_media_range(&self, media_range: &MediaRange) -> bool {
        if media_range == &::mime::STAR_STAR {
            true
        } else if media_range.subtype() == "*" {
            self.0.type_() == media_range.type_()
        } else {
            self == media_range
        }
    }

    pub fn into_media_range(self) -> MediaRange {
        self.0
    }
}

#[derive(Error, Debug)]
#[error("Could not parse media type: {}", .0)]
pub struct MediaTypeFromStrError(String);

impl FromStr for MediaType {
    type Err = MediaTypeFromStrError;
    fn from_str(input: &str) -> Result<Self, Self::Err> {
        let mime = Mime::from_str(input)
            .map_err(|error| MediaTypeFromStrError(format!("Malformed media type: {}", error)))?;
        MediaType::from_media_range(mime).ok_or_else(|| {
            MediaTypeFromStrError(String::from(
                "Input is a valid media range, but not a specific media type",
            ))
        })
    }
}

impl fmt::Debug for MediaType {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.0, formatter)
    }
}

impl fmt::Display for MediaType {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.0, formatter)
    }
}

impl Serialize for MediaType {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl PartialEq<MediaRange> for MediaType {
    fn eq(&self, other: &MediaRange) -> bool {
        &self.0 == other
    }
}

impl PartialEq<MediaType> for MediaRange {
    fn eq(&self, other: &MediaType) -> bool {
        self == &other.0
    }
}