-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathbest_target.rs
144 lines (127 loc) · 3.4 KB
/
best_target.rs
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
use std::fmt::Debug;
use ringboard_sdk::core::{is_plaintext_mime, protocol::MimeType};
#[derive(Copy, Clone, Debug)]
struct SeenMime<Id> {
id: Id,
has_params: bool,
}
#[derive(Default, Debug)]
struct KnownSeenMimes<Id> {
mimes: [Option<SeenMime<Id>>; 6],
always_none: Option<SeenMime<Id>>,
}
#[derive(Default, Debug)]
pub struct BestMimeTypeFinder<Id> {
seen: KnownSeenMimes<Id>,
best_mime: MimeType,
block_plain_text: bool,
}
mod id {
pub trait AsId {
type Id;
fn as_id(&self) -> Self::Id;
}
impl AsId for String {
type Id = *const u8;
fn as_id(&self) -> Self::Id {
self.as_ptr()
}
}
impl AsId for u32 {
type Id = Self;
fn as_id(&self) -> Self::Id {
*self
}
}
}
impl<Id: id::AsId<Id: Eq>> BestMimeTypeFinder<Id> {
pub fn add_mime(&mut self, mime: &MimeType, id: Id) {
let Self {
seen:
KnownSeenMimes {
mimes:
[
ref mut plain,
ref mut image,
ref mut x_special,
ref mut chromium_custom,
ref mut any_text,
ref mut other,
],
always_none: _,
},
ref mut best_mime,
block_plain_text,
} = *self;
let target = if is_plaintext_mime(mime) {
if block_plain_text {
return;
}
plain
} else if mime.starts_with("image/") {
image
} else if mime.starts_with("x-special/") {
x_special
} else if mime == "chromium/x-web-custom-data" {
chromium_custom
} else if mime.starts_with("text/") {
any_text
} else if mime.chars().next().is_none_or(char::is_lowercase) {
other
} else {
return;
};
let id_ = id.as_id();
if target.is_none() {
*target = Some(SeenMime {
id,
has_params: mime.contains(';'),
});
} else if let Some(SeenMime {
id: _,
has_params: true,
}) = target
&& !mime.contains(';')
{
*target = Some(SeenMime {
id,
has_params: false,
});
}
if self
.seen
.best()
.as_ref()
.map(|SeenMime { id, has_params: _ }| id)
.map(id::AsId::as_id)
== Some(id_)
{
*best_mime = *mime;
}
}
}
impl<Id> BestMimeTypeFinder<Id> {
pub fn block_plain_text(&mut self) {
self.block_plain_text = true;
}
pub fn pop_best(&mut self) -> Option<Id> {
self.seen
.best()
.take()
.map(|SeenMime { id, has_params: _ }| id)
}
}
impl<Id: Copy> BestMimeTypeFinder<Id> {
pub fn best(mut self) -> Option<(Id, MimeType)> {
(*self.seen.best()).map(|SeenMime { id, has_params: _ }| (id, self.best_mime))
}
}
impl<Id> KnownSeenMimes<Id> {
fn best(&mut self) -> &mut Option<SeenMime<Id>> {
let Self { mimes, always_none } = self;
mimes
.iter_mut()
.find(|m| m.is_some())
.unwrap_or(always_none)
}
}