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
use std::fmt::{Debug, Formatter, Result};

use path_tree::{Path, PathTree};

use viz_core::{BoxHandler, Method};

use crate::{Route, Router};

/// Store all final routes.
#[derive(Default)]
pub struct Tree(Vec<(Method, PathTree<BoxHandler>)>);

impl Tree {
    /// Find a handler by the HTTP method and the URI's path.
    #[must_use]
    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 })
    }

    /// Consumes the Tree, returning the wrapped value.
    #[must_use]
    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 {
                    if let Some(t) =
                        tree.as_mut().iter_mut().find_map(
                            |(m, t)| {
                                if *m == method {
                                    Some(t)
                                } else {
                                    None
                                }
                            },
                        )
                    {
                        let _ = t.insert(&path, handler);
                    } else {
                        let mut t = PathTree::new();
                        let _ = t.insert(&path, handler);
                        tree.as_mut().push((method, t));
                    }
                }
            }
        }
        tree
    }
}

impl Debug for Tree {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        self.as_ref()
            .iter()
            .fold(f.debug_struct("Tree"), |mut d, (m, t)| {
                d.field("method", m).field("paths", &t.node);
                d
            })
            .finish()
    }
}