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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
#![forbid(unsafe_code)]
mod path;
mod routes;
mod visitor;
pub use path::{Param, Span};
pub use visitor::{Found, VisitError};
use path::Pattern;
use routes::{Node, RouteEntry};
pub struct Router<T> {
/// A collection of nodes that represent the path segments of a route.
nodes: Vec<Node>,
/// A vector of routes associated with the nodes in the route tree.
routes: Vec<T>,
}
pub struct Endpoint<'a, T> {
router: &'a mut Router<T>,
key: usize,
}
impl<T> Router<T> {
pub fn new() -> Self {
let mut nodes = Vec::new();
let routes = Vec::new();
nodes.push(Node::new(Pattern::Root));
Self { nodes, routes }
}
/// Returns a reference to the route associated with the given key.
///
pub fn get(&self, key: usize) -> Option<&T> {
self.routes.get(key)
}
pub fn at(&mut self, path: &'static str) -> Endpoint<T> {
let mut segments = path::patterns(path);
let key = insert(self, &mut segments, 0);
Endpoint { router: self, key }
}
pub fn visit(&self, path: &str) -> Vec<Result<Found, VisitError>> {
let mut segments = Vec::with_capacity(8);
let mut results = Vec::with_capacity(8);
let nodes = &self.nodes;
path::split(&mut segments, path);
visitor::visit(&mut results, nodes, &segments, path);
results
}
}
impl<T> Router<T> {
/// Returns a mutable representation of a single node in the route store.
fn entry(&mut self, key: usize) -> RouteEntry<T> {
RouteEntry::new(self, key)
}
/// Pushes a new node into the store and returns the key of the newly
/// inserted node.
fn push(&mut self, node: Node) -> usize {
let key = self.nodes.len();
self.nodes.push(node);
key
}
/// Returns a shared reference to the node at the given `key`.
fn node(&self, key: usize) -> &Node {
&self.nodes[key]
}
/// Returns a mutable reference to the node at the given `key`.
fn node_mut(&mut self, key: usize) -> &mut Node {
&mut self.nodes[key]
}
/// Returns a mutable reference to the route at the given `key`.
///
fn get_mut(&mut self, key: usize) -> &mut T {
&mut self.routes[key]
}
/// Pushes a new route into the store and returns the index of the newly
/// inserted route.
fn push_route(&mut self, route: T) -> usize {
let index = self.routes.len();
self.routes.push(route);
index
}
}
impl<T> Default for Router<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> Endpoint<'_, T> {
pub fn at(&mut self, path: &'static str) -> Endpoint<T> {
let mut segments = path::patterns(path);
let key = insert(self.router, &mut segments, self.key);
Endpoint {
router: self.router,
key,
}
}
pub fn param(&self) -> Option<&Param> {
self.router.node(self.key).param()
}
/// Returns a mutable reference to the route associated with this `Endpoint`.
/// If the route does not exist, the route will be set to the result of the
/// provided closure `f`.
pub fn get_or_insert_route_with<F>(&mut self, f: F) -> &mut T
where
F: FnOnce() -> T,
{
// Get the index of the route associated with the current node or insert
// a new route by calling the provided closure `f` if it does not exist.
let route_index = self.router.entry(self.key).get_or_insert_route_with(f);
// Return a mutable reference to the route associated with this `Endpoint`.
self.router.get_mut(route_index)
}
}
fn insert<T, I>(router: &mut Router<T>, segments: &mut I, into_index: usize) -> usize
where
I: Iterator<Item = Pattern>,
{
// If the current node is a catch-all, we can skip the rest of the segments.
// In the future we may want to panic if the caller tries to insert a node
// into a catch-all node rather than silently ignoring the rest of the
// segments.
if let Pattern::Wildcard(_) = router.node(into_index).pattern {
for _ in segments {}
return into_index;
}
// If there are no more segments, we can return the current key.
let pattern = match segments.next() {
Some(value) => value,
None => return into_index,
};
// Check if the pattern already exists in the node at `current_key`. If it does,
// we can continue to the next segment.
for next_index in router.node(into_index).entries() {
if pattern == router.node(*next_index).pattern {
return insert(router, segments, *next_index);
}
}
let next_index = router.entry(into_index).push(Node::new(pattern));
// If the pattern does not exist in the node at `current_key`, we need to create
// a new node as a descendant of the node at `current_key` and then insert it
// into the store.
insert(router, segments, next_index)
}
#[cfg(test)]
mod tests {
use crate::path::Param;
use super::Router;
const PATHS: [&str; 4] = [
"/*path",
"/echo/*path",
"/articles/:id",
"/articles/:id/comments",
];
#[test]
fn test_router_visit() {
let mut router = Router::new();
for path in &PATHS {
let _ = router.at(path).get_or_insert_route_with(|| ());
}
{
let path = "/";
let matches: Vec<_> = router.visit(path);
assert_eq!(matches.len(), 2);
{
// /
// ^ as Pattern::Root
let found = matches[0].as_ref().unwrap();
let route = found.route.and_then(|key| router.get(key));
assert_eq!(route, None);
assert_eq!(found.param, None);
assert_eq!(found.at, None);
assert!(found.is_leaf);
}
{
// /
// ^ as Pattern::CatchAll("*path")
let found = matches[1].as_ref().unwrap();
let route = found.route.and_then(|key| router.get(key));
assert_eq!(route, Some(&()));
assert_eq!(found.param, Some(Param::new("path")));
assert_eq!(found.at, None);
// Should be considered exact because of the catch-all pattern.
assert!(found.is_leaf);
}
}
{
let path = "/not/a/path";
let matches: Vec<_> = router.visit(path);
assert_eq!(matches.len(), 2);
{
// /not/a/path
// ^ as Pattern::Root
let found = matches[0].as_ref().unwrap();
let route = found.route.and_then(|key| router.get(key));
assert_eq!(route, None);
assert_eq!(found.param, None);
assert_eq!(found.at, None);
assert!(!found.is_leaf);
}
{
// /not/a/path
// ^^^^^^^^^^ as Pattern::CatchAll("*path")
let found = matches[1].as_ref().unwrap();
let route = found.route.and_then(|key| router.get(key));
let segment = {
let range = found.at.as_ref().unwrap();
&path[range.start()..range.end()]
};
assert_eq!(route, Some(&()));
assert_eq!(found.param, Some(Param::new("path")));
assert_eq!(segment, &path[1..]);
// Should be considered exact because of the catch-all pattern.
assert!(found.is_leaf);
}
}
{
let path = "/echo/hello/world";
let matches: Vec<_> = router.visit(path);
assert_eq!(matches.len(), 4);
{
// /echo/hello/world
// ^ as Pattern::Root
let found = matches[0].as_ref().unwrap();
let route = found.route.and_then(|key| router.get(key));
assert_eq!(route, None);
assert_eq!(found.at, None);
assert_eq!(found.param, None);
assert!(!found.is_leaf);
}
{
// /echo/hello/world
// ^^^^^^^^^^^^^^^^ as Pattern::CatchAll("*path")
let found = matches[1].as_ref().unwrap();
let route = found.route.and_then(|key| router.get(key));
let segment = {
let range = found.at.as_ref().unwrap();
&path[range.start()..range.end()]
};
assert_eq!(route, Some(&()));
assert_eq!(found.param, Some(Param::new("path")));
assert_eq!(segment, &path[1..]);
// Should be considered exact because of the catch-all pattern.
assert!(found.is_leaf);
}
{
// /echo/hello/world
// ^^^^ as Pattern::Static("echo")
let found = matches[2].as_ref().unwrap();
let route = found.route.and_then(|key| router.get(key));
let segment = {
let range = found.at.as_ref().unwrap();
&path[range.start()..range.end()]
};
assert_eq!(route, None);
assert_eq!(found.param, None);
assert_eq!(segment, "echo");
assert!(!found.is_leaf);
}
{
// /echo/hello/world
// ^^^^^^^^^^^ as Pattern::CatchAll("*path")
let found = matches[3].as_ref().unwrap();
let route = found.route.and_then(|key| router.get(key));
let segment = {
let range = found.at.as_ref().unwrap();
&path[range.start()..range.end()]
};
assert_eq!(route, Some(&()));
assert_eq!(found.param, Some(Param::new("path")));
assert_eq!(segment, "hello/world");
assert!(found.is_leaf);
}
}
{
let path = "/articles/100";
let matches: Vec<_> = router.visit(path);
assert_eq!(matches.len(), 4);
{
// /articles/100
// ^ as Pattern::Root
let found = matches[0].as_ref().unwrap();
let route = found.route.and_then(|key| router.get(key));
assert_eq!(route, None);
assert_eq!(found.at, None);
assert_eq!(found.param, None);
assert!(!found.is_leaf);
}
{
// /articles/100
// ^^^^^^^^^^^^ as Pattern::CatchAll("*path")
let found = matches[1].as_ref().unwrap();
let route = found.route.and_then(|key| router.get(key));
let segment = {
let range = found.at.as_ref().unwrap();
&path[range.start()..range.end()]
};
assert_eq!(route, Some(&()));
assert_eq!(found.param, Some(Param::new("path")));
assert_eq!(segment, &path[1..]);
// Should be considered exact because of the catch-all pattern.
assert!(found.is_leaf);
}
{
// /articles/100
// ^^^^^^^^ as Pattern::Static("articles")
let found = matches[2].as_ref().unwrap();
let route = found.route.and_then(|key| router.get(key));
let segment = {
let range = found.at.as_ref().unwrap();
&path[range.start()..range.end()]
};
assert_eq!(route, None);
assert_eq!(found.param, None);
assert_eq!(segment, "articles");
assert!(!found.is_leaf);
}
{
// /articles/100
// ^^^ as Pattern::Dynamic(":id")
let found = matches[3].as_ref().unwrap();
let route = found.route.and_then(|key| router.get(key));
let segment = {
let range = found.at.as_ref().unwrap();
&path[range.start()..range.end()]
};
assert_eq!(route, Some(&()));
assert_eq!(found.param, Some(Param::new("id")));
assert_eq!(segment, "100");
assert!(found.is_leaf);
}
}
{
let path = "/articles/100/comments";
let matches: Vec<_> = router.visit(path);
assert_eq!(matches.len(), 5);
{
// /articles/100/comments
// ^ as Pattern::Root
let found = matches[0].as_ref().unwrap();
let route = found.route.and_then(|key| router.get(key));
assert_eq!(route, None);
assert_eq!(found.at, None);
assert_eq!(found.param, None);
assert!(!found.is_leaf);
}
{
// /articles/100/comments
// ^^^^^^^^^^^^^^^^^^^^^ as Pattern::CatchAll("*path")
let found = matches[1].as_ref().unwrap();
let route = found.route.and_then(|key| router.get(key));
let segment = {
let range = found.at.as_ref().unwrap();
&path[range.start()..range.end()]
};
assert_eq!(route, Some(&()));
assert_eq!(found.param, Some(Param::new("path")));
assert_eq!(segment, &path[1..]);
// Should be considered exact because of the catch-all pattern.
assert!(found.is_leaf);
}
{
// /articles/100/comments
// ^^^^^^^^ as Pattern::Static("articles")
let found = matches[2].as_ref().unwrap();
let route = found.route.and_then(|key| router.get(key));
let segment = {
let range = found.at.as_ref().unwrap();
&path[range.start()..range.end()]
};
assert_eq!(route, None);
assert_eq!(found.param, None);
assert_eq!(segment, "articles");
assert!(!found.is_leaf);
}
{
// /articles/100/comments
// ^^^ as Pattern::Dynamic(":id")
let found = matches[3].as_ref().unwrap();
let route = found.route.and_then(|key| router.get(key));
let segment = {
let range = found.at.as_ref().unwrap();
&path[range.start()..range.end()]
};
assert_eq!(route, Some(&()));
assert_eq!(found.param, Some(Param::new("id")));
assert_eq!(segment, "100");
assert!(!found.is_leaf);
}
{
// /articles/100/comments
// ^^^^^^^^ as Pattern::Static("comments")
let found = matches[4].as_ref().unwrap();
let route = found.route.and_then(|key| router.get(key));
let segment = {
let range = found.at.as_ref().unwrap();
&path[range.start()..range.end()]
};
assert_eq!(route, Some(&()));
assert_eq!(found.param, None);
assert_eq!(segment, "comments");
// Should be considered exact because it is the last path segment.
assert!(found.is_leaf);
}
}
}
}