Skip to main content

rocket/router/
router.rs

1use std::ops::{Deref, DerefMut};
2use std::collections::HashMap;
3use std::sync::atomic::{AtomicUsize, Ordering};
4
5use crate::request::Request;
6use crate::http::{Method, Status};
7use crate::{Route, Catcher};
8use crate::router::Collide;
9
10#[derive(Debug)]
11pub(crate) struct Router<T>(T);
12
13#[derive(Debug, Default)]
14pub struct Pending {
15    pub routes: Vec<Route>,
16    pub catchers: Vec<Catcher>,
17}
18
19#[derive(Debug, Default)]
20pub struct Finalized {
21    pub routes: Vec<Route>,
22    pub catchers: Vec<Catcher>,
23    route_map: HashMap<Method, Vec<RouteId>>,
24    catcher_map: HashMap<Option<u16>, Vec<usize>>,
25}
26
27/// Identifies a route in a finalized router. Only `finalize()` creates these.
28#[derive(Debug, Copy, Clone)]
29pub(crate) struct RouteId(usize);
30
31/// An optional `RouteId` that can be set through a shared reference.
32#[derive(Debug, Default)]
33pub(crate) struct AtomicRouteId(AtomicUsize);
34
35pub type Pair<T> = (T, T);
36
37pub type Collisions = (Vec<Pair<Route>>, Vec<Pair<Catcher>>);
38
39pub type Result<T, E = Collisions> = std::result::Result<T, E>;
40
41impl Router<Pending> {
42    pub fn new() -> Self {
43        Router(Pending::default())
44    }
45
46    pub fn finalize(self) -> Result<Router<Finalized>, Collisions> {
47        fn collisions<'a, T>(items: &'a [T]) -> impl Iterator<Item = (T, T)> + 'a
48            where T: Collide + Clone + 'a,
49        {
50            items.iter()
51                .enumerate()
52                .flat_map(move |(i, a)| {
53                    items.iter()
54                        .skip(i + 1)
55                        .filter(move |b| a.collides_with(b))
56                        .map(move |b| (a.clone(), b.clone()))
57                })
58        }
59
60        let route_collisions: Vec<_> = collisions(&self.routes).collect();
61        let catcher_collisions: Vec<_> = collisions(&self.catchers).collect();
62
63        if !route_collisions.is_empty() || !catcher_collisions.is_empty() {
64            return Err((route_collisions, catcher_collisions))
65        }
66
67        // create the route map
68        let mut route_map: HashMap<Method, Vec<RouteId>> = HashMap::new();
69        for (i, route) in self.routes.iter().enumerate() {
70            match route.method {
71                Some(method) => route_map.entry(method).or_default().push(RouteId(i)),
72                None => for method in Method::ALL_VARIANTS {
73                    route_map.entry(*method).or_default().push(RouteId(i));
74                }
75            }
76        }
77
78        // create the catcher map
79        let mut catcher_map: HashMap<Option<u16>, Vec<usize>> = HashMap::new();
80        for (i, catcher) in self.catchers.iter().enumerate() {
81            catcher_map.entry(catcher.code).or_default().push(i);
82        }
83
84        // sort routes by rank
85        for routes in route_map.values_mut() {
86            routes.sort_by_key(|&RouteId(i)| &self.routes[i].rank);
87        }
88
89        // sort catchers by rank
90        for catchers in catcher_map.values_mut() {
91            catchers.sort_by_key(|&i| &self.catchers[i].rank);
92        }
93
94        Ok(Router(Finalized {
95            routes: self.0.routes,
96            catchers: self.0.catchers,
97            route_map, catcher_map
98        }))
99    }
100}
101
102impl Router<Finalized> {
103    #[track_caller]
104    pub fn route<'r, 'a: 'r>(
105        &'a self,
106        req: &'r Request<'r>
107    ) -> impl Iterator<Item = (RouteId, &'a Route)> + 'r {
108        // Note that routes are presorted by ascending rank on each `add` and
109        // that all routes with `None` methods have been cloned into all methods.
110        self.route_map.get(&req.method())
111            .into_iter()
112            .flat_map(move |routes| routes.iter().map(move |&id| (id, &self.routes[id.0])))
113            .filter(move |(_, r)| r.matches(req))
114    }
115
116    pub fn get(&self, id: RouteId) -> Option<&Route> {
117        self.routes.get(id.0)
118    }
119
120    // For many catchers, using aho-corasick or similar should be much faster.
121    #[track_caller]
122    pub fn catch<'r>(&self, status: Status, req: &'r Request<'r>) -> Option<&Catcher> {
123        // Note that catchers are presorted by descending base length.
124        let explicit = self.catcher_map.get(&Some(status.code))
125            .map(|catchers| catchers.iter().map(|&i| &self.catchers[i]))
126            .and_then(|mut catchers| catchers.find(|c| c.matches(status, req)));
127
128        let default = self.catcher_map.get(&None)
129            .map(|catchers| catchers.iter().map(|&i| &self.catchers[i]))
130            .and_then(|mut catchers| catchers.find(|c| c.matches(status, req)));
131
132        match (explicit, default) {
133            (None, None) => None,
134            (None, c@Some(_)) | (c@Some(_), None) => c,
135            (Some(a), Some(b)) if a.rank <= b.rank => Some(a),
136            (Some(_), Some(b)) => Some(b),
137        }
138    }
139}
140
141impl AtomicRouteId {
142    pub fn load(&self) -> Option<RouteId> {
143        self.0.load(Ordering::Acquire).checked_sub(1).map(RouteId)
144    }
145
146    pub fn store(&self, id: RouteId) {
147        self.0.store(id.0 + 1, Ordering::Release)
148    }
149}
150
151impl Clone for AtomicRouteId {
152    fn clone(&self) -> Self {
153        AtomicRouteId(AtomicUsize::new(self.0.load(Ordering::Acquire)))
154    }
155}
156
157impl<T> Deref for Router<T> {
158    type Target = T;
159
160    fn deref(&self) -> &Self::Target {
161        &self.0
162    }
163}
164
165impl DerefMut for Router<Pending> {
166    fn deref_mut(&mut self) -> &mut Self::Target {
167        &mut self.0
168    }
169}
170
171#[cfg(test)]
172mod test {
173    use super::*;
174
175    use crate::route::dummy_handler;
176    use crate::local::blocking::Client;
177    use crate::http::{Method::*, uri::Origin};
178
179    fn make_router<I>(routes: I) -> Result<Router<Finalized>, Collisions>
180        where I: Iterator<Item = (Option<isize>, &'static str)>
181    {
182        let mut router = Router::new();
183        for (rank, route) in routes {
184            let route = Route::ranked(rank, Get, route, dummy_handler);
185            router.routes.push(route);
186        }
187
188        router.finalize()
189    }
190
191    fn router_with_routes(routes: &[&'static str]) -> Router<Finalized> {
192        make_router(routes.iter().map(|r| (None, *r))).unwrap()
193    }
194
195    fn router_with_ranked_routes(routes: &[(isize, &'static str)]) -> Router<Finalized> {
196        make_router(routes.iter().map(|r| (Some(r.0), r.1))).unwrap()
197    }
198
199    fn rankless_route_collisions(routes: &[&'static str]) -> bool {
200        make_router(routes.iter().map(|r| (Some(0), *r))).is_err()
201    }
202
203    fn default_rank_route_collisions(routes: &[&'static str]) -> bool {
204        make_router(routes.iter().map(|r| (None, *r))).is_err()
205    }
206
207    #[test]
208    fn test_rankless_collisions() {
209        assert!(rankless_route_collisions(&["/hello", "/hello"]));
210        assert!(rankless_route_collisions(&["/<a>", "/hello"]));
211        assert!(rankless_route_collisions(&["/<a>", "/<b>"]));
212        assert!(rankless_route_collisions(&["/hello/bob", "/hello/<b>"]));
213        assert!(rankless_route_collisions(&["/a/b/<c>/d", "/<a>/<b>/c/d"]));
214
215        assert!(rankless_route_collisions(&["/a/b", "/<a..>"]));
216        assert!(rankless_route_collisions(&["/a/b/c", "/a/<a..>"]));
217        assert!(rankless_route_collisions(&["/<a>/b", "/a/<a..>"]));
218        assert!(rankless_route_collisions(&["/a/<b>", "/a/<a..>"]));
219        assert!(rankless_route_collisions(&["/a/b/<c>", "/a/<a..>"]));
220        assert!(rankless_route_collisions(&["/<a..>", "/a/<a..>"]));
221        assert!(rankless_route_collisions(&["/a/<a..>", "/a/<a..>"]));
222        assert!(rankless_route_collisions(&["/a/b/<a..>", "/a/<a..>"]));
223        assert!(rankless_route_collisions(&["/a/b/c/d", "/a/<a..>"]));
224        assert!(rankless_route_collisions(&["/", "/<a..>"]));
225        assert!(rankless_route_collisions(&["/a/<_>", "/a/<a..>"]));
226        assert!(rankless_route_collisions(&["/a/<_>", "/a/<_..>"]));
227        assert!(rankless_route_collisions(&["/foo/bar/baz", "/foo/<_..>"]));
228
229        assert!(rankless_route_collisions(&["/<_>", "/<_>"]));
230        assert!(rankless_route_collisions(&["/a/<_>", "/a/b"]));
231        assert!(rankless_route_collisions(&["/a/<_>", "/a/<b>"]));
232        assert!(rankless_route_collisions(&["/<_..>", "/a/b"]));
233        assert!(rankless_route_collisions(&["/<_..>", "/<_>"]));
234        assert!(rankless_route_collisions(&["/<_>/b", "/a/b"]));
235        assert!(rankless_route_collisions(&["/", "/<foo..>"]));
236        assert!(rankless_route_collisions(&["/<_>", "/"]));
237    }
238
239    #[test]
240    fn test_collisions_normalize() {
241        assert!(rankless_route_collisions(&["//hello/", "/hello//"]));
242        assert!(rankless_route_collisions(&["/hello///bob", "/hello/<b>"]));
243        assert!(rankless_route_collisions(&["/a/<a..>//", "/a/<a..>"]));
244        assert!(rankless_route_collisions(&["/a/<a..>//", "/a/b//c//d/"]));
245        assert!(rankless_route_collisions(&["/<a..>//", "/a//<a..>"]));
246        assert!(rankless_route_collisions(&["/a/<a..>/", "/a/bd/e/"]));
247        assert!(rankless_route_collisions(&["/<a..>/", "/a/bd/e/"]));
248        assert!(rankless_route_collisions(&["//", "/<foo..>"]));
249        assert!(rankless_route_collisions(&["/a/<a..>//", "/a/b//c//d/e/"]));
250        assert!(rankless_route_collisions(&["/a//<a..>//", "/a/b//c//d/e/"]));
251        assert!(rankless_route_collisions(&["///<_>", "/<_>"]));
252        assert!(rankless_route_collisions(&["/a/<_>", "///a//b"]));
253        assert!(rankless_route_collisions(&["//a///<_>", "/a//<b>"]));
254        assert!(rankless_route_collisions(&["//<_..>", "/a/b"]));
255        assert!(rankless_route_collisions(&["//<_..>", "/<_>"]));
256        assert!(rankless_route_collisions(&["///<a>/", "/a/<a..>"]));
257        assert!(rankless_route_collisions(&["///<a..>/", "/a/<a..>"]));
258        assert!(rankless_route_collisions(&["/<a..>", "/hello"]));
259    }
260
261    #[test]
262    fn test_collisions_query() {
263        // Query shouldn't affect things when rankless.
264        assert!(rankless_route_collisions(&["/hello?<foo>", "/hello"]));
265        assert!(rankless_route_collisions(&["/<a>?foo=bar", "/hello?foo=bar&cat=fat"]));
266        assert!(rankless_route_collisions(&["/<a>?foo=bar", "/hello?foo=bar&cat=fat"]));
267        assert!(rankless_route_collisions(&["/<a>", "/<b>?<foo>"]));
268        assert!(rankless_route_collisions(&["/hello/bob?a=b", "/hello/<b>?d=e"]));
269        assert!(rankless_route_collisions(&["/<foo>?a=b", "/foo?d=e"]));
270        assert!(rankless_route_collisions(&["/<foo>?a=b&<c>", "/<foo>?d=e&<c>"]));
271        assert!(rankless_route_collisions(&["/<foo>?a=b&<c>", "/<foo>?d=e"]));
272    }
273
274    #[test]
275    fn test_no_collisions() {
276        assert!(!rankless_route_collisions(&["/a", "/a/"]));
277        assert!(!rankless_route_collisions(&["/<a>", "/hello//"]));
278        assert!(!rankless_route_collisions(&["/<a>", "/hello///"]));
279        assert!(!rankless_route_collisions(&["/hello/", "/hello"]));
280        assert!(!rankless_route_collisions(&["//hello/", "/hello"]));
281        assert!(!rankless_route_collisions(&["/a/b", "/a/b/c"]));
282        assert!(!rankless_route_collisions(&["/a/b/c/d", "/a/b/c/<d>/e"]));
283        assert!(!rankless_route_collisions(&["/a/d/<b..>", "/a/b/c"]));
284        assert!(!rankless_route_collisions(&["/a/<_>", "/a"]));
285        assert!(!rankless_route_collisions(&["/a/<_>", "/<_>"]));
286        assert!(!rankless_route_collisions(&["/a/<b>/<c..>", "/a/<c>"]));
287        assert!(!rankless_route_collisions(&["/<_>", "/a/<_..>"]));
288        assert!(!rankless_route_collisions(&["/foo", "/foo/<_..>"]));
289        assert!(!rankless_route_collisions(&["/a/<_..>", "/<_>"]));
290        assert!(!rankless_route_collisions(&["/a/<_..>", "/a"]));
291        assert!(!rankless_route_collisions(&["/<a>", "/a/<a..>"]));
292        assert!(!rankless_route_collisions(&["/a/d/<b..>", "/a/d"]));
293    }
294
295    #[test]
296    fn test_no_collision_when_ranked() {
297        assert!(!default_rank_route_collisions(&["/<_>", "/"]));
298        assert!(!default_rank_route_collisions(&["/<a>", "/hello"]));
299        assert!(!default_rank_route_collisions(&["/hello/bob", "/hello/<b>"]));
300        assert!(!default_rank_route_collisions(&["/a/b/c/d", "/<a>/<b>/c/d"]));
301        assert!(!default_rank_route_collisions(&["/hi", "/<hi>"]));
302        assert!(!default_rank_route_collisions(&["/a", "/a/<path..>"]));
303        assert!(!default_rank_route_collisions(&["/", "/<path..>"]));
304        assert!(!default_rank_route_collisions(&["/a/b", "/a/b/<c..>"]));
305        assert!(!default_rank_route_collisions(&["/<_>", "/static"]));
306        assert!(!default_rank_route_collisions(&["/<_..>", "/static"]));
307        assert!(!default_rank_route_collisions(&["/<path..>", "/"]));
308        assert!(!default_rank_route_collisions(&["/<_>/<_>", "/foo/bar"]));
309        assert!(!default_rank_route_collisions(&["/foo/<_>", "/foo/bar"]));
310
311        assert!(!default_rank_route_collisions(&["/<a>/<b>", "/hello/<b>"]));
312        assert!(!default_rank_route_collisions(&["/<a>/<b..>", "/hello/<b>"]));
313        assert!(!default_rank_route_collisions(&["/<a..>", "/hello/<b>"]));
314        assert!(!default_rank_route_collisions(&["/<a..>", "/hello"]));
315        assert!(!default_rank_route_collisions(&["/<a>", "/a/<path..>"]));
316        assert!(!default_rank_route_collisions(&["/a/<b>/c", "/<d>/<c..>"]));
317        assert!(!default_rank_route_collisions(&["/a/<b>/<c..>", "/a/<c>"]));
318    }
319
320    #[test]
321    fn test_collision_when_ranked() {
322        assert!(default_rank_route_collisions(&["/<a>/b", "/a/<b>"]));
323    }
324
325    #[test]
326    fn test_collision_when_ranked_query() {
327        assert!(default_rank_route_collisions(&["/a?a=b", "/a?c=d"]));
328        assert!(default_rank_route_collisions(&["/a?a=b&<b>", "/a?<c>&c=d"]));
329        assert!(default_rank_route_collisions(&["/a?a=b&<b..>", "/a?<c>&c=d"]));
330    }
331
332    #[test]
333    fn test_no_collision_when_ranked_query() {
334        assert!(!default_rank_route_collisions(&["/", "/?<c..>"]));
335        assert!(!default_rank_route_collisions(&["/hi", "/hi?<c>"]));
336        assert!(!default_rank_route_collisions(&["/hi", "/hi?c"]));
337        assert!(!default_rank_route_collisions(&["/hi?<c>", "/hi?c"]));
338        assert!(!default_rank_route_collisions(&["/<foo>?a=b", "/<foo>?c=d&<d>"]));
339    }
340
341    #[track_caller]
342    fn matches<'a>(router: &'a Router<Finalized>, method: Method, uri: &'a str) -> Vec<&'a Route> {
343        let client = Client::debug_with(vec![]).expect("client");
344        let request = client.req(method, Origin::parse(uri).unwrap());
345        router.route(&request).map(|(_, route)| route).collect()
346    }
347
348    #[track_caller]
349    fn route<'a>(router: &'a Router<Finalized>, method: Method, uri: &'a str) -> Option<&'a Route> {
350        matches(router, method, uri).into_iter().next()
351    }
352
353    #[test]
354    fn test_ok_routing() {
355        let router = router_with_routes(&["/hello"]);
356        assert!(route(&router, Get, "/hello").is_some());
357
358        let router = router_with_routes(&["/<a>"]);
359        assert!(route(&router, Get, "/").is_some());
360        assert!(route(&router, Get, "/hello").is_some());
361        assert!(route(&router, Get, "/hi").is_some());
362        assert!(route(&router, Get, "/bobbbbbbbbbby").is_some());
363        assert!(route(&router, Get, "/dsfhjasdf").is_some());
364
365        let router = router_with_routes(&["/<a>/<b>"]);
366        assert!(route(&router, Get, "/hello/hi").is_some());
367        assert!(route(&router, Get, "/i/a").is_some());
368        assert!(route(&router, Get, "/jdlk/asdij").is_some());
369        assert!(route(&router, Get, "/a/").is_some());
370
371        let mut router = Router::new();
372        router.routes.push(Route::new(Put, "/hello", dummy_handler));
373        router.routes.push(Route::new(Post, "/hello", dummy_handler));
374        router.routes.push(Route::new(Delete, "/hello", dummy_handler));
375        let router = router.finalize().unwrap();
376        assert!(route(&router, Put, "/hello").is_some());
377        assert!(route(&router, Post, "/hello").is_some());
378        assert!(route(&router, Delete, "/hello").is_some());
379
380        let router = router_with_routes(&["/<a..>"]);
381        assert!(route(&router, Get, "/").is_some());
382        assert!(route(&router, Get, "//").is_some());
383        assert!(route(&router, Get, "/hi").is_some());
384        assert!(route(&router, Get, "/hello/hi").is_some());
385        assert!(route(&router, Get, "/a/b/").is_some());
386        assert!(route(&router, Get, "/i/a").is_some());
387        assert!(route(&router, Get, "/a/b/c/d/e/f").is_some());
388
389        let router = router_with_routes(&["/foo/<a..>"]);
390        assert!(route(&router, Get, "/foo").is_none());
391        assert!(route(&router, Get, "/foo/").is_some());
392        assert!(route(&router, Get, "/foo///bar").is_some());
393    }
394
395    #[test]
396    fn test_err_routing() {
397        let router = router_with_routes(&["/hello"]);
398        assert!(route(&router, Put, "/hello").is_none());
399        assert!(route(&router, Post, "/hello").is_none());
400        assert!(route(&router, Options, "/hello").is_none());
401        assert!(route(&router, Get, "/hell").is_none());
402        assert!(route(&router, Get, "/hi").is_none());
403        assert!(route(&router, Get, "/hello/there").is_none());
404        assert!(route(&router, Get, "/hello/i").is_none());
405        assert!(route(&router, Get, "/hillo").is_none());
406
407        let router = router_with_routes(&["/<a>"]);
408        assert!(route(&router, Put, "/hello").is_none());
409        assert!(route(&router, Post, "/hello").is_none());
410        assert!(route(&router, Options, "/hello").is_none());
411        assert!(route(&router, Get, "/hello/").is_none());
412        assert!(route(&router, Get, "/hello/there/").is_none());
413        assert!(route(&router, Get, "/hello/there/").is_none());
414
415        let router = router_with_routes(&["/<a>/<b>"]);
416        assert!(route(&router, Get, "/a/b/c").is_none());
417        assert!(route(&router, Get, "/a").is_none());
418        assert!(route(&router, Get, "/a/b/c/d").is_none());
419        assert!(route(&router, Get, "/a/b/").is_none());
420        assert!(route(&router, Put, "/hello/hi").is_none());
421        assert!(route(&router, Put, "/a/b").is_none());
422
423        let router = router_with_routes(&["/prefix/<a..>"]);
424        assert!(route(&router, Get, "/").is_none());
425        assert!(route(&router, Get, "/prefi/").is_none());
426    }
427
428    /// Asserts that `$to` routes to `$want` given `$routes` are present.
429    macro_rules! assert_ranked_match {
430        ($routes:expr, $to:expr => $want:expr) => ({
431            let router = router_with_routes($routes);
432            let route_path = route(&router, Get, $to).unwrap().uri.to_string();
433            assert_eq!(route_path, $want.to_string(),
434                "\nmatched {} with {}, wanted {} in {:#?}", $to, route_path, $want, router);
435        })
436    }
437
438    #[test]
439    fn test_default_ranking() {
440        assert_ranked_match!(&["/hello", "/<name>"], "/hello" => "/hello");
441        assert_ranked_match!(&["/<name>", "/hello"], "/hello" => "/hello");
442        assert_ranked_match!(&["/<a>", "/hi", "/hi/<b>"], "/hi" => "/hi");
443        assert_ranked_match!(&["/<a>/b", "/hi/c"], "/hi/c" => "/hi/c");
444        assert_ranked_match!(&["/<a>/<b>", "/hi/a"], "/hi/c" => "/<a>/<b>");
445        assert_ranked_match!(&["/hi/a", "/hi/<c>"], "/hi/c" => "/hi/<c>");
446        assert_ranked_match!(&["/a", "/a?<b>"], "/a?b=c" => "/a?<b>");
447        assert_ranked_match!(&["/a", "/a?<b>"], "/a" => "/a?<b>");
448        assert_ranked_match!(&["/a", "/<a>", "/a?<b>", "/<a>?<b>"], "/a" => "/a?<b>");
449        assert_ranked_match!(&["/a", "/<a>", "/a?<b>", "/<a>?<b>"], "/b" => "/<a>?<b>");
450        assert_ranked_match!(&["/a", "/<a>", "/a?<b>", "/<a>?<b>"], "/b?v=1" => "/<a>?<b>");
451        assert_ranked_match!(&["/a", "/<a>", "/a?<b>", "/<a>?<b>"], "/a?b=c" => "/a?<b>");
452        assert_ranked_match!(&["/a", "/a?b"], "/a?b" => "/a?b");
453        assert_ranked_match!(&["/<a>", "/a?b"], "/a?b" => "/a?b");
454        assert_ranked_match!(&["/a", "/<a>?b"], "/a?b" => "/a");
455        assert_ranked_match!(&["/a?<c>&b", "/a?<b>"], "/a" => "/a?<b>");
456        assert_ranked_match!(&["/a?<c>&b", "/a?<b>"], "/a?b" => "/a?<c>&b");
457        assert_ranked_match!(&["/a?<c>&b", "/a?<b>"], "/a?c" => "/a?<b>");
458        assert_ranked_match!(&["/", "/<foo..>"], "/" => "/");
459        assert_ranked_match!(&["/", "/<foo..>"], "/hi" => "/<foo..>");
460        assert_ranked_match!(&["/hi", "/<foo..>"], "/hi" => "/hi");
461    }
462
463    fn ranked_collisions(routes: &[(isize, &'static str)]) -> bool {
464        make_router(routes.iter().map(|r| (Some(r.0), r.1))).is_err()
465    }
466
467    #[test]
468    fn test_no_manual_ranked_collisions() {
469        assert!(!ranked_collisions(&[(1, "/a/<b>"), (2, "/a/<b>")]));
470        assert!(!ranked_collisions(&[(0, "/a/<b>"), (2, "/a/<b>")]));
471        assert!(!ranked_collisions(&[(5, "/a/<b>"), (2, "/a/<b>")]));
472        assert!(!ranked_collisions(&[(1, "/a/<b>"), (1, "/b/<b>")]));
473        assert!(!ranked_collisions(&[(1, "/a/<b..>"), (2, "/a/<b..>")]));
474        assert!(!ranked_collisions(&[(0, "/a/<b..>"), (2, "/a/<b..>")]));
475        assert!(!ranked_collisions(&[(5, "/a/<b..>"), (2, "/a/<b..>")]));
476        assert!(!ranked_collisions(&[(1, "/<a..>"), (2, "/<a..>")]));
477    }
478
479    #[test]
480    fn test_ranked_collisions() {
481        assert!(ranked_collisions(&[(2, "/a/<b..>"), (2, "/a/<b..>")]));
482        assert!(ranked_collisions(&[(2, "/a/c/<b..>"), (2, "/a/<b..>")]));
483        assert!(ranked_collisions(&[(2, "/<b..>"), (2, "/a/<b..>")]));
484    }
485
486    macro_rules! assert_ranked_routing {
487        (to: $to:expr, with: $routes:expr, expect: $($want:expr),+) => ({
488            let router = router_with_ranked_routes(&$routes);
489            let routed_to = matches(&router, Get, $to);
490            let expected = &[$($want),+];
491            assert_eq!(routed_to.len(), expected.len());
492            for (got, expected) in routed_to.iter().zip(expected.iter()) {
493                assert_eq!(got.rank, expected.0);
494                assert_eq!(got.uri.to_string(), expected.1.to_string());
495            }
496        })
497    }
498
499    #[test]
500    fn test_ranked_routing() {
501        assert_ranked_routing!(
502            to: "/a/b",
503            with: [(1, "/a/<b>"), (2, "/a/<b>")],
504            expect: (1, "/a/<b>"), (2, "/a/<b>")
505        );
506
507        assert_ranked_routing!(
508            to: "/b/b",
509            with: [(1, "/a/<b>"), (2, "/b/<b>"), (3, "/b/b")],
510            expect: (2, "/b/<b>"), (3, "/b/b")
511        );
512
513        assert_ranked_routing!(
514            to: "/b/b",
515            with: [(2, "/b/<b>"), (1, "/a/<b>"), (3, "/b/b")],
516            expect: (2, "/b/<b>"), (3, "/b/b")
517        );
518
519        assert_ranked_routing!(
520            to: "/b/b",
521            with: [(3, "/b/b"), (2, "/b/<b>"), (1, "/a/<b>")],
522            expect: (2, "/b/<b>"), (3, "/b/b")
523        );
524
525        assert_ranked_routing!(
526            to: "/b/b",
527            with: [(1, "/a/<b>"), (2, "/b/<b>"), (0, "/b/b")],
528            expect: (0, "/b/b"), (2, "/b/<b>")
529        );
530
531        assert_ranked_routing!(
532            to: "/profile/sergio/edit",
533            with: [(1, "/<a>/<b>/edit"), (2, "/profile/<d>"), (0, "/<a>/<b>/<c>")],
534            expect: (0, "/<a>/<b>/<c>"), (1, "/<a>/<b>/edit")
535        );
536
537        assert_ranked_routing!(
538            to: "/profile/sergio/edit",
539            with: [(0, "/<a>/<b>/edit"), (2, "/profile/<d>"), (5, "/<a>/<b>/<c>")],
540            expect: (0, "/<a>/<b>/edit"), (5, "/<a>/<b>/<c>")
541        );
542
543        assert_ranked_routing!(
544            to: "/a/b",
545            with: [(0, "/a/b"), (1, "/a/<b..>")],
546            expect: (0, "/a/b"), (1, "/a/<b..>")
547        );
548
549        assert_ranked_routing!(
550            to: "/a/b/c/d/e/f",
551            with: [(1, "/a/<b..>"), (2, "/a/b/<c..>")],
552            expect: (1, "/a/<b..>"), (2, "/a/b/<c..>")
553        );
554
555        assert_ranked_routing!(
556            to: "/hi/",
557            with: [(1, "/hi/<foo..>"), (0, "/hi/<foo>")],
558            expect: (0, "/hi/<foo>"), (1, "/hi/<foo..>")
559        );
560    }
561
562    macro_rules! assert_default_ranked_routing {
563        (to: $to:expr, with: $routes:expr, expect: $($want:expr),+) => ({
564            let router = router_with_routes(&$routes);
565            let routed_to = matches(&router, Get, $to);
566            let expected = &[$($want),+];
567            assert!(routed_to.len() == expected.len());
568            for (got, expected) in routed_to.iter().zip(expected.iter()) {
569                assert_eq!(got.uri.to_string(), expected.to_string());
570            }
571        })
572    }
573
574    #[test]
575    fn test_default_ranked_routing() {
576        assert_default_ranked_routing!(
577            to: "/a/b?v=1",
578            with: ["/a/<b>", "/a/b"],
579            expect: "/a/b", "/a/<b>"
580        );
581
582        assert_default_ranked_routing!(
583            to: "/a/b?v=1",
584            with: ["/a/<b>", "/a/b", "/a/b?<v>"],
585            expect: "/a/b?<v>", "/a/b", "/a/<b>"
586        );
587
588        assert_default_ranked_routing!(
589            to: "/a/b?v=1",
590            with: ["/a/<b>", "/a/b", "/a/b?<v>", "/a/<b>?<v>"],
591            expect: "/a/b?<v>", "/a/b", "/a/<b>?<v>", "/a/<b>"
592        );
593
594        assert_default_ranked_routing!(
595            to: "/a/b",
596            with: ["/a/<b>", "/a/b", "/a/b?<v>", "/a/<b>?<v>"],
597            expect: "/a/b?<v>", "/a/b", "/a/<b>?<v>", "/a/<b>"
598        );
599
600        assert_default_ranked_routing!(
601            to: "/a/b?c",
602            with: ["/a/b", "/a/b?<c>", "/a/b?c", "/a/<b>?c", "/a/<b>?<c>", "/<a>/<b>"],
603            expect: "/a/b?c", "/a/b?<c>", "/a/b", "/a/<b>?c", "/a/<b>?<c>", "/<a>/<b>"
604        );
605    }
606
607    fn router_with_catchers(catchers: &[(Option<u16>, &str)]) -> Result<Router<Finalized>> {
608        let mut router = Router::new();
609        for (code, base) in catchers {
610            let catcher = Catcher::new(*code, crate::catcher::dummy_handler);
611            router.catchers.push(catcher.map_base(|_| base.to_string()).unwrap());
612        }
613
614        router.finalize()
615    }
616
617    #[track_caller]
618    fn catcher<'a>(r: &'a Router<Finalized>, status: Status, uri: &str) -> Option<&'a Catcher> {
619        let client = Client::debug_with(vec![]).expect("client");
620        let request = client.get(Origin::parse(uri).unwrap());
621        r.catch(status, &request)
622    }
623
624    macro_rules! assert_catcher_routing {
625        (
626            catch: [$(($code:expr, $uri:expr)),+],
627            reqs: [$($r:expr),+],
628            with: [$(($ecode:expr, $euri:expr)),+]
629        ) => ({
630            let catchers = vec![$(($code.into(), $uri)),+];
631            let requests = vec![$($r),+];
632            let expected = vec![$(($ecode.into(), $euri)),+];
633
634            let router = router_with_catchers(&catchers).expect("valid router");
635            for (req, expected) in requests.iter().zip(expected.iter()) {
636                let req_status = Status::from_code(req.0).expect("valid status");
637                let catcher = catcher(&router, req_status, req.1).expect("some catcher");
638                assert_eq!(catcher.code, expected.0,
639                    "\nmatched {:?}, expected {:?} for req {:?}", catcher, expected, req);
640
641                assert_eq!(catcher.base.path(), expected.1,
642                    "\nmatched {:?}, expected {:?} for req {:?}", catcher, expected, req);
643            }
644        })
645    }
646
647    #[test]
648    fn test_catcher_routing() {
649        // Check that the default `/` catcher catches everything.
650        assert_catcher_routing! {
651            catch: [(None, "/")],
652            reqs: [(404, "/a/b/c"), (500, "/a/b"), (415, "/a/b/d"), (422, "/a/b/c/d?foo")],
653            with: [(None, "/"), (None, "/"), (None, "/"), (None, "/")]
654        }
655
656        // Check prefixes when they're exact.
657        assert_catcher_routing! {
658            catch: [(None, "/"), (None, "/a"), (None, "/a/b")],
659            reqs: [
660                (404, "/"), (500, "/"),
661                (404, "/a"), (500, "/a"),
662                (404, "/a/b"), (500, "/a/b")
663            ],
664            with: [
665                (None, "/"), (None, "/"),
666                (None, "/a"), (None, "/a"),
667                (None, "/a/b"), (None, "/a/b")
668            ]
669        }
670
671        // Check prefixes when they're not exact.
672        assert_catcher_routing! {
673            catch: [(None, "/"), (None, "/a"), (None, "/a/b")],
674            reqs: [
675                (404, "/foo"), (500, "/bar"), (422, "/baz/bar"), (418, "/poodle?yes"),
676                (404, "/a/foo"), (500, "/a/bar/baz"), (510, "/a/c"), (423, "/a/c/b"),
677                (404, "/a/b/c"), (500, "/a/b/c/d"), (500, "/a/b?foo"), (400, "/a/b/yes")
678            ],
679            with: [
680                (None, "/"), (None, "/"), (None, "/"), (None, "/"),
681                (None, "/a"), (None, "/a"), (None, "/a"), (None, "/a"),
682                (None, "/a/b"), (None, "/a/b"), (None, "/a/b"), (None, "/a/b")
683            ]
684        }
685
686        // Check that we prefer specific to default.
687        assert_catcher_routing! {
688            catch: [(400, "/"), (404, "/"), (None, "/")],
689            reqs: [
690                (400, "/"), (400, "/bar"), (400, "/foo/bar"),
691                (404, "/"), (404, "/bar"), (404, "/foo/bar"),
692                (405, "/"), (405, "/bar"), (406, "/foo/bar")
693            ],
694            with: [
695                (400, "/"), (400, "/"), (400, "/"),
696                (404, "/"), (404, "/"), (404, "/"),
697                (None, "/"), (None, "/"), (None, "/")
698            ]
699        }
700
701        // Check that we prefer longer prefixes over specific.
702        assert_catcher_routing! {
703            catch: [(None, "/a/b"), (404, "/a"), (422, "/a")],
704            reqs: [
705                (404, "/a/b"), (404, "/a/b/c"), (422, "/a/b/c"),
706                (404, "/a"), (404, "/a/c"), (404, "/a/cat/bar"),
707                (422, "/a"), (422, "/a/c"), (422, "/a/cat/bar")
708            ],
709            with: [
710                (None, "/a/b"), (None, "/a/b"), (None, "/a/b"),
711                (404, "/a"), (404, "/a"), (404, "/a"),
712                (422, "/a"), (422, "/a"), (422, "/a")
713            ]
714        }
715
716        // Just a fun one.
717        assert_catcher_routing! {
718            catch: [(None, "/"), (None, "/a/b"), (500, "/a/b/c"), (500, "/a/b")],
719            reqs: [(404, "/a/b/c"), (500, "/a/b"), (400, "/a/b/d"), (500, "/a/b/c/d?foo")],
720            with: [(None, "/a/b"), (500, "/a/b"), (None, "/a/b"), (500, "/a/b/c")]
721        }
722
723        // Check that bases, like routes, aren't percent-decoded when matching.
724        assert_catcher_routing! {
725            catch: [(None, "/"), (None, "/m%20n"), (None, "/häcker")],
726            reqs: [
727                (404, "/m%2520n"), (404, "/m%2520n/x"), (404, "/m%20n/x"),
728                (404, "/h%C3%A4cker"), (404, "/h%C3%A4cker/x"), (404, "/h%25C3%25A4cker/x")
729            ],
730            with: [
731                (None, "/m%20n"), (None, "/m%20n"), (None, "/"),
732                (None, "/häcker"), (None, "/häcker"), (None, "/")
733            ]
734        }
735    }
736}