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 itertools::Itertools;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum MediaTypeMatch {
Full,
SubStar,
Star,
None,
}
#[derive(Debug, Clone, PartialEq)]
pub struct MediaType {
pub main: String,
pub sub: String,
pub weight: f32,
}
impl MediaType {
pub fn parse_string(media_type: &str) -> MediaType {
let types: Vec<&str> = media_type.splitn(2, '/').collect_vec();
if types.is_empty() || types[0].is_empty() {
MediaType {
main: "*".to_string(),
sub: "*".to_string(),
weight: 1.0,
}
} else {
MediaType {
main: types[0].to_string(),
sub: if types.len() == 1 || types[1].is_empty() {
"*".to_string()
} else {
types[1].to_string()
},
weight: 1.0,
}
}
}
pub fn with_weight(&self, weight: &String) -> MediaType {
MediaType {
main: self.main.clone(),
sub: self.sub.clone(),
weight: weight.parse().unwrap_or(1.0),
}
}
pub fn weight(&self) -> (f32, u8) {
if self.main == "*" && self.sub == "*" {
(self.weight, 2)
} else if self.sub == "*" {
(self.weight, 1)
} else {
(self.weight, 0)
}
}
pub fn matches(&self, other: &MediaType) -> MediaTypeMatch {
if other.main == "*" {
MediaTypeMatch::Star
} else if self.main == other.main && other.sub == "*" {
MediaTypeMatch::SubStar
} else if self.main == other.main && self.sub == other.sub {
MediaTypeMatch::Full
} else {
MediaTypeMatch::None
}
}
pub fn to_string(&self) -> String {
format!("{}/{}", self.main, self.sub)
}
}