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
use std::fmt::{Debug, Formatter, Result};
use path_tree::{Path, PathTree};
use viz_core::{BoxHandler, Method};
use crate::{Route, Router};
#[derive(Default)]
pub struct Tree(Vec<(Method, PathTree<BoxHandler>)>);
impl Tree {
pub fn find<'a, 'b>(
&'a self,
method: &'b Method,
path: &'b str,
) -> Option<(&'a BoxHandler, Path<'a, 'b>)> {
self.0
.iter()
.find_map(|(m, t)| if m == method { t.find(path) } else { None })
}
pub fn into_inner(self) -> Vec<(Method, PathTree<BoxHandler>)> {
self.0
}
}
impl AsRef<Vec<(Method, PathTree<BoxHandler>)>> for Tree {
fn as_ref(&self) -> &Vec<(Method, PathTree<BoxHandler>)> {
&self.0
}
}
impl AsMut<Vec<(Method, PathTree<BoxHandler>)>> for Tree {
fn as_mut(&mut self) -> &mut Vec<(Method, PathTree<BoxHandler>)> {
&mut self.0
}
}
impl From<Router> for Tree {
fn from(router: Router) -> Self {
let mut tree = Tree::default();
if let Some(routes) = router.routes {
for (mut path, Route { methods }) in routes {
if !path.starts_with('/') {
path.insert(0, '/');
}
for (method, handler) in methods {
match tree.as_mut().iter_mut().find_map(|(m, t)| {
if *m == method {
Some(t)
} else {
None
}
}) {
Some(t) => {
t.insert(&path, handler);
}
None => {
let mut t = PathTree::new();
t.insert(&path, handler);
tree.as_mut().push((method, t));
}
}
}
}
}
tree
}
}
impl Debug for Tree {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
f.debug_struct("Tree").finish()
}
}