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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
use std::collections::HashMap;
use std::fmt::Debug;
use std::fmt::Error;
use std::fmt::Formatter;
use std::str::FromStr;
use virtual_dom_rs::VText;
use virtual_dom_rs::View;
use virtual_dom_rs::VirtualNode;
pub trait RouteParam {
fn from_str_param(param: &str) -> Result<Self, &str>
where
Self: Sized;
}
impl<T> RouteParam for T
where
T: FromStr,
{
fn from_str_param(param: &str) -> Result<T, &str> {
match param.parse::<T>() {
Ok(parsed) => Ok(parsed),
Err(_) => Err(param),
}
}
}
pub type ParseRouteParam = Box<Fn(&str, &str) -> Option<Box<dyn RouteParam>>>;
pub struct Route {
route_definition: &'static str,
route_param_parser: ParseRouteParam,
}
impl Debug for Route {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
f.write_str(self.route_definition);
Ok(())
}
}
impl Route {
pub fn new(route_definition: &'static str, route_param_parser: ParseRouteParam) -> Route {
Route {
route_definition,
route_param_parser,
}
}
}
impl Route {
pub fn matches(&self, path: &str) -> bool {
let defined_segments = self
.route_definition
.split("/")
.filter(|segment| segment.len() > 0)
.collect::<Vec<&str>>();
let incoming_segments = path
.split("/")
.filter(|segment| segment.len() > 0)
.collect::<Vec<&str>>();
if defined_segments.len() != incoming_segments.len() {
return false;
}
for (index, defined_segment) in defined_segments.iter().enumerate() {
if defined_segment.len() == 0 {
continue;
}
let mut chars = defined_segment.chars();
let first_char = chars.next().unwrap();
if first_char == ':' {
let param_name = chars.collect::<String>();
let incoming_param_value = incoming_segments[index];
return (self.route_param_parser)(param_name.as_str(), incoming_param_value)
.is_some();
}
let incoming_segment = incoming_segments[index];
if defined_segment != &incoming_segment {
return false;
}
}
true
}
pub fn view(&self, incoming_path: &str) -> VirtualNode {
VirtualNode::Text(VText::new("TODO: Implement this"))
}
pub fn find_route_param<'a>(&self, incoming_path: &'a str, param_key: &str) -> Option<&'a str> {
let param_key = format!(":{}", param_key);
let mut incoming_segments = incoming_path.split("/");
for (idx, defined_segment) in self.route_definition.split("/").enumerate() {
if defined_segment == ¶m_key {
for _ in 0..idx {
incoming_segments.next().unwrap();
}
return Some(incoming_segments.next().unwrap());
}
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
use std::rc::Rc;
use virtual_dom_rs::html;
use virtual_dom_rs::VirtualNode;
struct MyView {
id: u32,
}
impl View for MyView {
fn render(&self) -> VirtualNode {
let id = VirtualNode::text(self.id.to_string());
html! { <div> {id} </div> }
}
}
#[test]
fn route_type_safety() {
MatchRouteTestCase {
desc: "Typed route parameters",
route_definition: "/users/:id",
matches: vec![
("/users/5", true, "5 should match since it is a u32"),
(
"/users/foo",
false,
"foo should not match since it is not a u32",
),
],
}
.test();
}
#[test]
fn route_cascade() {
MatchRouteTestCase {
desc: "Make sure that `/` route doesn't capture `/other-routes`",
route_definition: "/",
matches: vec![("/foo", false, "routes should not match additional segments")],
}
.test();
}
#[test]
fn find_route_param() {
let route = Route::new(
"/:id",
Box::new(|param_key, param_val| {
if param_key == "id" {
Some(Box::new(u32::from_str_param(param_val).unwrap()));
}
None
}),
);
assert_eq!(route.find_route_param("/5", "id"), Some("5"));
}
struct MatchRouteTestCase {
desc: &'static str,
route_definition: &'static str,
matches: Vec<(&'static str, bool, &'static str)>,
}
impl MatchRouteTestCase {
fn test(&self) {
fn get_param(param_key: &str, param_val: &str) -> Option<Box<dyn RouteParam>> {
match param_key {
"id" => match u32::from_str_param(param_val) {
Ok(num) => Some(Box::new(num)),
Err(_) => None,
},
_ => None,
}
}
let route = Route::new(self.route_definition, Box::new(get_param));
for match_case in self.matches.iter() {
assert_eq!(
route.matches(match_case.0),
match_case.1,
"{}\n{}",
self.desc,
match_case.2
);
}
}
}
}