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
pub mod error;
#[cfg(test)]
pub mod tests;
use error::RouterError;
use regex::Regex;
use std::collections::HashMap;
pub struct Route<'a, V> {
regex: &'a str,
params: Vec<&'a str>,
handlers: HashMap<&'a str, V>,
}
impl<'a, V> Route<'a, V> {
pub fn new(regex: &'a str, params: Vec<&'a str>) -> Self {
Route {
regex,
params,
handlers: HashMap::new(),
}
}
pub fn set(&mut self, method: &'a str, handler: V) {
self.handlers.insert(method, handler);
}
pub fn regex(&self) -> &str {
self.regex
}
pub fn params(&self) -> &[&str] {
&self.params
}
pub fn handlers(&self) -> &HashMap<&'a str, V> {
&self.handlers
}
}
pub struct RouteMatch<'a, V> {
handler: &'a V,
params: HashMap<&'a str, &'a str>,
}
impl<'a, V> RouteMatch<'a, V> {
pub fn handler(&self) -> &'a V {
self.handler
}
pub fn params<'b>(&'b self) -> &'b HashMap<&'a str, &'a str> {
&self.params
}
}
pub struct Router<'a, V> {
regex: Regex,
routes: Vec<Option<Route<'a, V>>>,
}
impl<'a, V> Router<'a, V> {
fn new(mut builder: RouterBuilder<'a, V>) -> Result<Self, RouterError> {
if builder.routes.is_empty() {
return Err(RouterError::EmptyRouterError);
}
let mut routes = Vec::new();
let combined_regex = construct_combined_regex(&builder.routes);
let regex = Regex::new(&combined_regex)?;
while !builder.routes.is_empty() {
let route = builder.routes.remove(0);
let param_len = route.params().len();
routes.push(Some(route));
for _ in 0..param_len {
routes.push(None);
}
}
Ok(Self { regex, routes })
}
pub fn dispatch<'b>(&'b self, method: &'b str, path: &'b str) -> Option<RouteMatch<'b, V>> {
let captures = self.regex.captures(&path)?;
let mut first_match: Option<usize> = None;
for group in 1..captures.len() {
if captures.get(group).is_some() {
first_match = Some(group);
break;
}
}
let route = self.routes.get(first_match? - 1).unwrap().as_ref().unwrap();
let handler = route.handlers.get(method)?;
let mut params: HashMap<&str, &str> = HashMap::with_capacity(route.params.len());
for i in 0..route.params().len() {
let key = route.params().get(i).unwrap();
let value = captures.get(first_match? + i + 1).unwrap().as_str();
params.insert(key, value);
}
Some(RouteMatch { handler, params })
}
pub fn routes(&self) -> impl Iterator<Item = &Route<'a, V>> {
self.routes.iter().filter(|route| route.is_some()).map(|route| route.as_ref().unwrap())
}
}
pub struct RouterBuilder<'a, V> {
routes: Vec<Route<'a, V>>,
}
impl<'a, V> RouterBuilder<'a, V> {
pub fn new() -> Self {
RouterBuilder { routes: Vec::new() }
}
pub fn define(&mut self, route: Route<'a, V>) {
self.routes.push(route);
}
pub fn build(self) -> Result<Router<'a, V>, RouterError> {
Router::new(self)
}
}
impl<'a, V> Default for RouterBuilder<'a, V> {
fn default() -> Self {
Self::new()
}
}
fn construct_combined_regex<V>(routes: &[Route<V>]) -> String {
let mut combined_regex = String::new();
for route in routes {
combined_regex.push_str("(^");
combined_regex.push_str(route.regex);
combined_regex.push_str("$)|");
}
combined_regex.pop();
combined_regex
}
#[macro_export]
macro_rules! route {
($builder:ident; $route:expr; $($param:expr),*; $($method:expr => $handler:expr),+) => {{
let mut route = $crate::Route::new($route, vec![$($param,)*]);
$(route.set($method, $handler);)+
$builder.define(route);
}};
}