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
pub struct Tree<'a, T> {
label: &'a str,
value: Option<(T, Vec<&'a str>)>,
branches: Vec<Tree<'a, T>>
}
impl<'a, T> Tree<'a, T> {
pub fn new<'b>() -> Tree<'b, T> {
Tree {
label: "",
value: None,
branches: Vec::new()
}
}
pub fn add(&mut self, key: &'a str, value: T) {
let segments = key.split('/').filter(|s| !s.is_empty());
let capture_labels = Vec::new();
self.add_(segments, value, capture_labels);
}
fn add_<I: Iterator<Item=&'a str>>(
&mut self, mut segments: I, value: T,
mut capture_labels: Vec<&'a str>) {
match segments.next() {
None => {
if self.value.is_some() {
panic!("Duplicate route!");
}
self.value = Some((value, capture_labels))
},
Some(segment) => {
if let Some(existing_branch) =
self.branches.iter_mut().find(|t| t.label == segment) {
existing_branch.add_(segments, value, capture_labels);
return;
}
if segment.starts_with(':') {
capture_labels.push(&segment[1..]);
if let Some(existing_branch) =
self.branches.iter_mut().find(|t| t.label.is_empty()) {
existing_branch.add_(
segments, value, capture_labels);
return;
}
let mut branch = Tree {
label: "",
value: None,
branches: Vec::new()
};
branch.add_(segments, value, capture_labels);
self.branches.push(branch);
} else {
let mut branch = Tree {
label: segment,
value: None,
branches: Vec::new()
};
branch.add_(segments, value, capture_labels);
self.branches.push(branch);
}
}
}
}
pub fn find<'b>(
&self,
key: &'b str
) -> Option<(&T, Vec<(&'a str, &'b str)>)> {
let segments: Vec<&str> = key.split('/')
.filter(|s| !s.is_empty())
.collect();
let mut captured = Vec::new();
self.find_(segments.as_slice(), &mut captured)
.map(|&(ref v, ref labels)| {
(v, labels.iter().cloned().zip(captured).collect())
})
}
fn find_<'b>(
&self,
segments: &[&'b str],
captured: &mut Vec<&'b str>
) -> Option<&(T, Vec<&'a str>)> {
match segments.split_first() {
None => self.value.as_ref(),
Some((&segment, remaining)) => self.branches.iter().filter_map(|t| {
if t.label == segment {
t.find_(remaining, captured)
} else if t.label == "" {
captured.push(segment);
let result = t.find_(remaining, captured);
if result.is_none() {
captured.pop();
}
result
} else {
None
}
}).next()
}
}
}
#[cfg(test)]
mod tests {
use Tree;
#[test]
fn can_add_and_find() {
let mut routes = Tree::new();
routes.add("/", 0);
routes.add("/var", 1);
routes.add("/var/www", 11);
routes.add("/var/log", 12);
assert_eq!(routes.find("/vax"), None);
assert_eq!(routes.find("/var/something"), None);
assert_eq!(
routes.find("////"),
Some((&0, vec![])));
assert_eq!(
routes.find("//var//"),
Some((&1, vec![])));
assert_eq!(
routes.find("/var/www/"),
Some((&11, vec![])));
assert_eq!(
routes.find("/var/log/"),
Some((&12, vec![])));
}
#[test]
fn can_add_and_capture_and_find() {
let mut routes = Tree::new();
routes.add("/user/:username", 11);
routes.add("/user/:username/:intent/show", 111);
routes.add("/user/:username/profile", 112);
assert_eq!(routes.find("/user/myname/delete"), None);
assert_eq!(routes.find("/user/myname/cook/throw"), None);
assert_eq!(
routes.find("/user/myname"),
Some((&11, vec![("username", "myname")])));
assert_eq!(
routes.find("/user/myname/profile"),
Some((&112, vec![("username", "myname")])));
assert_eq!(
routes.find("/user/myname/cook/show"),
Some((&111, vec![
("username", "myname"),
("intent", "cook")
])));
}
#[test]
fn can_add_and_capture_and_find_handlers() {
let mut routes = Tree::new();
let handler = |captured: Vec<(&str, &str)>| {
assert_eq!(captured.len(), 2);
assert_eq!(captured[0].0, "folder");
assert_eq!(captured[0].1, "myfolder");
assert_eq!(captured[1].0, "file");
assert_eq!(captured[1].1, "myfile");
};
routes.add("home/:folder/:file", handler);
match routes.find("/home/myfolder/myfile") {
None => assert!(false),
Some((fx, captured)) => fx(captured)
}
}
}