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
use std::collections::HashMap;

use crate::context::Context;
use crate::route_tree::RouteTree;

use thruster_core_async_await::{MiddlewareChain};

pub struct MatchedRoute<'a, T: 'static + Context + Send> {
  pub middleware: &'a MiddlewareChain<T>,
  pub value: String,
  pub params: HashMap<String, String>,
  pub query_params: HashMap<String, String>,
}

pub struct RouteParser<T: 'static + Context + Send> {
  pub route_tree: RouteTree<T>,
  pub shortcuts: HashMap<String, MiddlewareChain<T>>
}

impl<T: Context + Send> RouteParser<T> {
  pub fn new() -> RouteParser<T> {
    RouteParser {
      route_tree: RouteTree::new(),
      shortcuts: HashMap::new()
    }
  }

  pub fn add_method_agnostic_middleware(&mut self, route: &str, middleware: MiddlewareChain<T>) {
    self.route_tree.add_use_node(route, middleware);
  }

  pub fn add_route(&mut self, route: &str, middleware: MiddlewareChain<T>) {
    self.route_tree.add_route(route, middleware);
  }

  pub fn optimize(&mut self) {
    let routes = self.route_tree.root_node.get_route_list();

    for (path, middleware, is_terminal_node) in routes {
      if is_terminal_node {
        self.shortcuts.insert((&path[1..]).to_owned(), middleware);
      }
    }
  }

  #[inline]
  pub fn match_route(&self, route: &str) -> MatchedRoute<T> {
    let query_params = HashMap::new();

    let split_route = route.find('?');
    let mut route = match split_route {
      Some(index) => &route[0..index],
      None => route
    };

    // Trim trailing slashes
    while &route[route.len() - 1..route.len()] == "/" {
      route = &route[0..route.len() - 1];
    }

    if let Some(shortcut) = self.shortcuts.get(route) {
      MatchedRoute {
        middleware: shortcut,
        value: route.to_owned(),
        params: HashMap::new(),
        query_params
      }
    } else {
      let matched = self.route_tree.match_route(route);

      MatchedRoute {
        middleware: matched.1,
        value: route.to_owned(),
        params: matched.0,
        query_params
      }
    }
  }
}

impl<T: Context + Send> Default for RouteParser<T> {
  fn default() -> RouteParser<T> {
    RouteParser::new()
  }
}