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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
use std::collections::HashMap;
use std::ascii::AsciiExt;

use http::Method;
use http::Request;
use http::Response;
use super::Handle;

pub struct Route {
    pattern: String,
    method: Method,
    handle: Box<Handle>,
    compilied_pattern: String,
    paths: HashMap<String, usize>,
}

impl Route {
    pub fn new(method: Method, pattern: String, handle: Box<Handle>) -> Route {
        let mut route = Route {
            pattern: pattern.clone(),
            method: method,
            handle: handle,
            compilied_pattern: String::default(),
            paths: HashMap::new(),
        };

        route.re_connfigure(pattern);

        route
    }

    pub fn pattern(&self) -> &String {
        &self.pattern
    }

    pub fn method(&self) -> &Method {
        &self.method
    }

    pub fn compilied_pattern(&self) -> String {
        self.compilied_pattern.clone()
    }

    pub fn name(&mut self, name: &str) {
        println!("{:?}", name);
        println!("{:?}", self.method);
    }

    pub fn path(&self) -> HashMap<String, usize> {
        self.paths.clone()
    }

    pub fn execute(&self, request: &mut Request, response: &mut Response) {
        (self.handle)(request, response);
    }

    fn re_connfigure(&mut self, pattern: String) {
        
        let prce_pattern;

        if pattern.contains("{") {
            let (route, route_paths) = extract_named_params(&pattern).unwrap();
            self.paths = route_paths;

            prce_pattern = route;
        } else {
            prce_pattern = pattern;
        }

        self.compilied_pattern = compile_pattern(prce_pattern);
    }
}

pub struct Group {
    pub routes: Vec<Route>,
    prefix: String,
}

impl Group {
    pub fn new(prefix: &str) -> Group {
        Group {
            routes: Vec::new(),
            prefix: prefix.to_owned(),
        }
    }

    fn add<H>(&mut self, method: &str, pattern: &str, handle: H) -> &mut Route
        where H: Fn(&mut Request, &mut Response) + Send + Sync + 'static
    {
        let route = Route::new(
            method.parse().unwrap(), 
            self.prefix.clone() + pattern,
            Box::new(handle),
        );

        self.routes.push(route);
        self.routes.last_mut().unwrap()
    }

    pub fn get<H>(&mut self, pattern: &str, handle: H) -> &mut Route
        where H: Fn(&mut Request, &mut Response) + Send + Sync + 'static
    {
        self.add("GET", pattern, handle)
    }

    pub fn post<H>(&mut self, pattern: &str, handle: H) -> &mut Route
        where H: Fn(&mut Request, &mut Response) + Send + Sync + 'static
    {
        self.add("POST", pattern, handle)
    }

    pub fn put<H>(&mut self, pattern: &str, handle: H) -> &mut Route
        where H: Fn(&mut Request, &mut Response) + Send + Sync + 'static
    {
        self.add("PUT", pattern, handle)
    }

    pub fn delete<H>(&mut self, pattern: &str, handle: H) -> &mut Route
        where H: Fn(&mut Request, &mut Response) + Send + Sync + 'static
    {
        self.add("DELETE", pattern, handle)
    }

    pub fn option<H>(&mut self, pattern: &str, handle: H) -> &mut Route
        where H: Fn(&mut Request, &mut Response) + Send + Sync + 'static
    {
        self.add("OPTION", pattern, handle)
    }

    pub fn head<H>(&mut self, pattern: &str, handle: H) -> &mut Route
        where H: Fn(&mut Request, &mut Response) + Send + Sync + 'static
    {
        self.add("HEAD", pattern, handle)
    }
}

fn extract_named_params(pattern: &str) -> Result<(String, HashMap<String, usize>), ()> {
    
    let mut parenthese_count = 0;
    let mut bracket_count = 0;
    let mut intermediate = 0;
    let mut marker = 0;  
    let mut number_matches = 0;
    let mut tmp;
    let mut found_pattern;
    
    let mut prev_ch = '\0';
    let mut variable;
    let mut regexp;
    let mut item;
    let mut route = "".to_string();

    let mut not_valid = false;

    let mut matches = HashMap::new();

    if !pattern.is_ascii() {
        panic!("{:?}", "The ruote pattern must be an ascii");
    }
    
    for (cursor, ch) in pattern.chars().enumerate() {
        if parenthese_count == 0 {
            if ch == '{' {
                if bracket_count == 0 {
                    marker = cursor + 1;
                    intermediate = 0;
                    not_valid = false;
                }

                bracket_count += 1;
            } else {
                if ch == '}' {
                    bracket_count -= 1;
                    if intermediate > 0 {
                        if bracket_count == 0 {

                            number_matches += 1;
                            variable = "";
                            regexp = "";
                            item = &pattern[marker..cursor];

                            for (cursor_var, ch) in item.chars().enumerate() {
                                if ch == '\0' {
                                    break;
                                }

                                if cursor_var == 0 && !( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
                                    not_valid = true;
                                    break;
                                }

                                if (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '-' || ch == '_' || ch == ':' {
                                    if ch == ':' {
                                        let (first, last) = item.split_at(cursor_var);
                                        variable = first;
                                        regexp = &last[1..];
                                        break;
                                    }
                                } else {
                                    not_valid = true;
                                    break;
                                }
                            }

                            if !not_valid {
                                tmp = number_matches;
                                if !variable.is_empty() && !regexp.is_empty() {

                                    found_pattern = 0;
                                    for regexp_ch in regexp.chars() {
                                        if regexp_ch == '\0' {
                                            break;
                                        }

                                        if found_pattern == 0 {
                                            if regexp_ch == '(' {
                                                found_pattern = 1;
                                            }
                                        } else {
                                            if regexp_ch == ')' {
                                                found_pattern = 2;
                                                break;
                                            }
                                        }
                                    }

                                    if found_pattern != 2 {
                                        route.push('(');
                                        route += regexp;
                                        route.push(')');
                                    } else {
                                        route += regexp;
                                    }
                                    matches.insert(variable.to_string(), tmp);
                                } else {
                                    route += "([^/]*)";
                                    matches.insert(item.to_string(), tmp);
                                }
                                
                            } else {
                                route.push('{');
                                route += item;
                                route.push('}');
                            }
                            continue;
                        }
                    }

                }
            }
        }

        if bracket_count == 0 {
            if ch == '(' {
                parenthese_count += 1;
            } else {
                if ch == ')' {
                    parenthese_count -= 1;
                    if parenthese_count == 0 {
                        number_matches += 1;
                    }
                }
            }
        }

        if bracket_count > 0 {
            intermediate += 1;
        } else {
            if parenthese_count == 0 && prev_ch != '\\' {
                if ch == '.' || ch == '+' || ch == '|' || ch == '#' {
                    route = route + "\\";
                }
            }
            route.push(ch);
            prev_ch = ch;
        }
    }

    Ok((route, matches))
}

fn compile_pattern(pattern: String) -> String {
    
    let mut tmp = String::default();
    
    if pattern.contains("(") || pattern.contains("["){
        tmp.push('^');
        tmp += &pattern;
        tmp.push('$');

        return tmp;
    }

    pattern
}