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
use crate::{Error, FromHtml, HtmlNode};
pub trait Mapper<T>: Sized {
type Structure<U>;
type Error<E: Error>: Error;
fn try_map<N: HtmlNode>(
source: Self::Structure<N>,
args: &T::Args,
) -> Result<Self, Self::Error<T::Error>>
where
T: FromHtml;
}
impl<T> Mapper<T> for T
where
T: FromHtml,
{
type Structure<U> = U;
type Error<E: Error> = E;
fn try_map<N: HtmlNode>(
source: Self::Structure<N>,
args: &T::Args,
) -> Result<Self, Self::Error<T::Error>>
where
T: FromHtml,
{
T::from_html(&source, args)
}
}
impl<T> Mapper<T> for Option<T> {
type Structure<U> = Option<U>;
type Error<E: Error> = E;
fn try_map<N>(source: Self::Structure<N>, args: &T::Args) -> Result<Self, Self::Error<T::Error>>
where
T: FromHtml,
N: HtmlNode,
{
source
.as_ref()
.map(|n| T::from_html(n, args))
.map_or(Ok(None), |v| v.map(Some))
}
}
impl<T> Mapper<T> for Vec<T> {
type Structure<U> = Vec<U>;
type Error<E: Error> = ListElementError<E>;
fn try_map<N>(source: Self::Structure<N>, args: &T::Args) -> Result<Self, Self::Error<T::Error>>
where
T: FromHtml,
N: HtmlNode,
{
source
.iter()
.enumerate()
.map(|(i, n)| {
T::from_html(n, args).map_err(|e| ListElementError { index: i, error: e })
})
.fold(Ok(vec![]), |acc, res| {
acc.and_then(|mut list| {
res.map(|val| {
list.push(val);
list
})
})
})
}
}
impl<T, const M: usize> Mapper<T> for [T; M] {
type Structure<U> = [U; M];
type Error<E: Error> = ListElementError<E>;
fn try_map<N>(source: Self::Structure<N>, args: &T::Args) -> Result<Self, Self::Error<T::Error>>
where
T: FromHtml,
N: HtmlNode,
{
let v = source
.iter()
.enumerate()
.map(|(i, n)| {
T::from_html(n, args).map_err(|e| ListElementError { index: i, error: e })
})
.fold(Ok(vec![]), |acc, res| {
acc.and_then(|mut list| {
res.map(|val| {
list.push(val);
list
})
})
})?;
Ok(v.try_into().map_err(|_| "").unwrap())
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ListElementError<E: Error> {
pub index: usize,
pub error: E,
}
#[cfg(test)]
mod test {
use super::*;
use crate::CssSelector;
use crate::Never;
#[test]
fn vec() {
assert_eq!(
Vec::<FromHtmlImpl>::try_map(vec![MockElement("a"), MockElement("b")], &()),
Ok(vec![FromHtmlImpl::new("a"), FromHtmlImpl::new("b")]),
"the method is applied for each items of the vec"
);
assert_eq!(
Vec::<FromHtmlImpl>::try_map(vec![MockElement("a"), MockElement("!b")], &()),
Err(ListElementError {
index: 1,
error: "!b".to_string()
}),
"returned error if one of the vec items fails to apply"
);
}
#[test]
fn option() {
assert_eq!(
Option::<FromHtmlImpl>::try_map::<MockElement>(Some(MockElement("ok!")), &()),
Ok(Some(FromHtmlImpl::new("ok!"))),
"the method is applied for is present"
);
assert_eq!(
Option::<FromHtmlImpl>::try_map::<MockElement>(None, &()),
Ok(None),
"returned none if none"
);
assert_eq!(
Option::<FromHtmlImpl>::try_map::<MockElement>(Some(MockElement("!err")), &()),
Err("!err".to_string()),
"returned error if failed to apply"
);
}
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct FromHtmlImpl(String);
impl FromHtmlImpl {
pub fn new<S: AsRef<str>>(s: S) -> Self {
Self(s.as_ref().to_string())
}
}
impl FromHtml for FromHtmlImpl {
type Args = ();
type Error = String;
fn from_html<N>(source: &N, _args: &Self::Args) -> Result<Self, Self::Error>
where
N: HtmlNode,
{
let text = source.text_contents();
if text.starts_with('!') {
Err(text)
} else {
Ok(FromHtmlImpl(text))
}
}
}
#[derive(Clone)]
pub struct MockElement(&'static str);
pub struct MockSelector;
impl CssSelector for MockSelector {
type Error = Never;
fn parse<S>(_s: S) -> Result<Self, Self::Error>
where
S: AsRef<str>,
{
unimplemented!()
}
}
impl HtmlNode for MockElement {
type Selector = MockSelector;
fn select(&self, _selector: &Self::Selector) -> Vec<Self> {
unimplemented!()
}
fn text_contents(&self) -> String {
self.0.to_string()
}
fn attribute<S>(&self, _attr: S) -> Option<&str>
where
S: AsRef<str>,
{
unimplemented!()
}
}
}