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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
use std::collections::HashMap;
use thiserror::Error;
pub use crate::route::parse::Parser;
pub mod param_type;
pub mod parse;
pub use param_type::ParamType;
#[derive(Debug, Clone, PartialEq)]
pub struct Route {
pub name: String,
pub path: Vec<Segment>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Segment {
Empty,
Constant(String),
Param(Param),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Param {
pub name: String,
pub kind: ParamType,
}
#[derive(Error, Debug)]
pub enum CheckError {
#[error("malformed path: {0}")]
MalformedPath(String),
}
impl Route {
/// Check if a path matches this route.
///
/// # Examples
///
/// ```
/// use routem::{Parser, Route};
///
/// let parser = Parser::default();
/// let route = parser.route("user-route", "/user/<id:int>/").unwrap();
///
/// assert!(route.check("/user/123/"));
/// assert!(!route.check("/user/123"));
/// assert!(!route.check("/user/123/def"));
/// assert!(!route.check("/user/abc/"));
/// ```
pub fn check(&self, path: &str) -> bool {
let clean_path: &str = path.strip_prefix('/').unwrap_or(path);
let parts = clean_path.split('/').collect::<Vec<&str>>();
if parts.len() != self.path.len() {
return false;
}
for (part, segment) in parts.iter().zip(self.path.iter()) {
match segment {
Segment::Empty => {
if !part.is_empty() {
return false;
}
}
Segment::Constant(s) => {
if part != s {
return false;
}
}
Segment::Param(p) => {
if !(p.kind.check)(part) {
return false;
}
}
}
}
true
}
/// If a path matches the route, returns the matching params. Otherwise,
/// returns None.
///
/// # Examples
///
/// ```
/// use routem::{Parser, Route};
///
/// let parser = Parser::default();
/// let route = parser.route("user-route", "/user/<id:int>/").unwrap();
///
/// assert_eq!(route.extract_param_list("/user/123/"), Some(vec!["123".to_string()]));
/// ```
pub fn extract_param_list(&self, path: &str) -> Option<Vec<String>> {
let clean_path: &str = path.strip_prefix('/').unwrap_or(path);
let parts = clean_path.split('/').collect::<Vec<&str>>();
if parts.len() != self.path.len() {
return None;
}
let mut params = Vec::new();
for (part, segment) in parts.iter().zip(self.path.iter()) {
match segment {
Segment::Empty => {
if !part.is_empty() {
return None;
}
}
Segment::Constant(s) => {
if part != s {
return None;
}
}
Segment::Param(_) => {
params.push(part.to_string());
}
}
}
Some(params)
}
/// Extracts the params from this route into a HashMap, with the key as the
/// parameter name.
///
/// # Examples
///
/// ```
/// use routem::{Parser, Route};
/// use std::collections::HashMap;
///
/// let parser = Parser::default();
///
/// let route = parser.route("user-route", "/user/<id:int>/").unwrap();
/// let params = route.extract_param_map("/user/123/").unwrap();
/// let mut expected = HashMap::new();
/// expected.insert("id".to_string(), "123".to_string());
/// assert_eq!(params, expected);
///
/// let route = parser.route("long-route", "/user/<id:int>/profile/<profile_id:string>").unwrap();
/// let params = route.extract_param_map("/user/123/profile/abc").unwrap();
/// let mut expected = HashMap::new();
/// expected.insert("id".to_string(), "123".to_string());
/// expected.insert("profile_id".to_string(), "abc".to_string());
/// assert_eq!(params, expected);
/// ```
pub fn extract_param_map(&self, path: &str) -> Result<HashMap<String, String>, CheckError> {
let clean_path: &str = path.strip_prefix('/').unwrap_or(path);
let parts = clean_path.split('/').collect::<Vec<&str>>();
if parts.len() != self.path.len() {
return Err(CheckError::MalformedPath(path.to_string()));
}
let mut params = HashMap::new();
for (part, segment) in parts.iter().zip(self.path.iter()) {
match segment {
Segment::Empty => {
if !part.is_empty() {
return Err(CheckError::MalformedPath(path.to_string()));
}
}
Segment::Constant(s) => {
if part != s {
return Err(CheckError::MalformedPath(path.to_string()));
}
}
Segment::Param(p) => {
params.insert(p.name.clone(), part.to_string());
}
}
}
Ok(params)
}
/// Fills the supplies parameters into the route. Returns None if the
/// provided params are the incorrect length.
///
/// # Examples
/// ```
/// use routem::{Parser, Route};
///
/// let parser = Parser::default();
///
/// let route = parser.route("user-route", "/user/<id:int>/").unwrap();
/// let params = vec!["123".to_string()];
/// assert_eq!(route.fill(¶ms), Some("/user/123/".to_string()));
///
/// let route = parser.route("long-route", "/user/<id:int>/profile/<profile_id:uuid>").unwrap();
/// let params = vec!["123".to_string(), "abc".to_string()];
/// assert_eq!(route.fill(¶ms), Some("/user/123/profile/abc".to_string()));
///
/// let route = parser.route("empty-route", "/").unwrap();
/// let params = vec![];
/// assert_eq!(route.fill(¶ms), Some("/".to_string()));
///
/// let route = parser.route("user-route", "/user/<id:int>/").unwrap();
/// let params = vec![];
/// assert_eq!(route.fill(¶ms), None);
/// let params = vec!["123".to_string(), "abc".to_string()];
/// assert_eq!(route.fill(¶ms), None);
/// ```
pub fn fill(&self, params: &[String]) -> Option<String> {
let mut path = String::new();
let mut index = 0;
for segment in self.path.iter() {
path.push('/');
match segment {
Segment::Empty => {}
Segment::Constant(s) => {
path.push_str(s);
}
Segment::Param(_) => {
if index >= params.len() {
return None;
}
path.push_str(¶ms[index]);
index += 1;
}
}
}
if index < params.len() {
return None;
}
Some(path)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_route() {
let input = "/user/<id:int>/";
let expected = vec![
Segment::Constant("user".to_string()),
Segment::Param(Param {
name: "id".to_string(),
kind: param_type::INT_PARAM,
}),
Segment::Empty,
];
let name = "user-route";
let parser = Parser::default();
let route = parser.route(name, input);
assert!(route.is_ok(), "{:#?}", route);
let route = route.unwrap();
assert_eq!(route.name, name);
assert_eq!(route.path, expected);
}
#[test]
fn test_parse_empty_route() {
let input = "/";
let expected = vec![Segment::Empty];
let name = "empty-route";
let parser = Parser::default();
let route = parser.route(name, input);
assert!(route.is_ok(), "{:#?}", route);
let route = route.unwrap();
assert_eq!(route.name, name);
assert_eq!(route.path, expected);
}
#[test]
fn test_parse_long_route() {
let input = "/user/<id:int>/profile/<profile_id:uuid>";
let expected = vec![
Segment::Constant("user".to_string()),
Segment::Param(Param {
name: "id".to_string(),
kind: param_type::INT_PARAM,
}),
Segment::Constant("profile".to_string()),
Segment::Param(Param {
name: "profile_id".to_string(),
kind: param_type::UUID_PARAM,
}),
];
let name = "long-route";
let parser = Parser::default();
let route = parser.route(name, input);
assert!(route.is_ok(), "{:#?}", route);
let route = route.unwrap();
assert_eq!(route.name, name);
assert_eq!(route.path, expected);
}
#[test]
fn test_check_simple_route() {
let parser = Parser::default();
let route = parser.route("user-route", "/user/<id:int>/").unwrap();
println!("{}", route.check("/user/123/"));
assert!(route.check("/user/123/"));
assert!(!route.check("/user/123"));
assert!(!route.check("/user/123/def"));
assert!(!route.check("/user/abc/"));
}
}