confetti 0.1.4

Framework for creating webapps using CloudFlare Workers
Documentation
use futures::future::Future;
use regex::{Captures, Regex};
use std::borrow::Cow;
use std::ops::Deref;
use std::pin::Pin;

use crate::conn::Conn;
use crate::web::Method;

pub type Pattern = (Method, &'static str);

pub struct Matcher {
    _path: Cow<'static, str>,
    regex: Regex,
}

pub struct Route {
    pub pattern: Pattern,
    pub middlewares: Vec<fn(Conn) -> Pin<Box<dyn Future<Output = Conn>>>>,
}

pub fn match_route(routes: &Vec<Route>, conn_method: Method, conn_path: String) -> Option<&Route> {
    return routes.iter().find(|route| {
        let (method, path) = route.pattern.clone();
        let matcher: Matcher = path.into();
        return method == conn_method && matcher.is_match(conn_path.as_str());
    });
}

impl Matcher {
    pub fn new<P: Into<Cow<'static, str>>>(path: P, regex: Regex) -> Matcher {
        Matcher {
            _path: path.into(),
            regex: regex,
        }
    }

    pub fn _path(&self) -> &str {
        &self._path
    }
}

impl Deref for Matcher {
    type Target = Regex;

    fn deref(&self) -> &Regex {
        &self.regex
    }
}

impl From<Regex> for Matcher {
    fn from(regex: Regex) -> Matcher {
        let path = regex.as_str().to_string();
        Matcher::new(path, regex)
    }
}

impl<'a> From<&'a str> for Matcher {
    fn from(s: &'a str) -> Matcher {
        From::from(s.to_string())
    }
}

static FORMAT_VAR: &'static str = ":format";
static VAR_SEQ: &'static str = "[,a-zA-Z0-9_-]*";
static VAR_SEQ_WITH_SLASH: &'static str = "[,/a-zA-Z0-9_-]*";
static REGEX_PARAM_SEQ: &'static str = "(\\?[a-zA-Z0-9%_=&-]*)?";

impl From<String> for Matcher {
    fn from(s: String) -> Matcher {
        let with_format = if s.contains(FORMAT_VAR) {
            s
        } else {
            format!("{}(\\.{})?", s, FORMAT_VAR)
        };

        // First mark all double wildcards for replacement. We can't directly
        // replace them since the replacement does contain the * symbol as well,
        // which would get overwritten with the next replace call
        let with_placeholder = with_format.replace("**", "___DOUBLE_WILDCARD___");

        // Then replace the regular wildcard symbols (*) with the appropriate regex
        let star_replaced = with_placeholder.replace("*", VAR_SEQ);

        // Now replace the previously marked double wild cards (**)
        let wildcarded = star_replaced.replace("___DOUBLE_WILDCARD___", VAR_SEQ_WITH_SLASH);

        // Add a named capture for each :(variable) symbol
        let regex_var_seq: Regex = Regex::new(r":([,a-zA-Z0-9_-]*)").unwrap();
        let named_captures = regex_var_seq.replace_all(&wildcarded, |captures: &Captures| {
            // There should only ever be one match (after subgroup 0)
            let c = captures.iter().skip(1).next().unwrap();
            format!("(?P<{}>[,a-zA-Z0-9%_-]*)", c.unwrap().as_str())
        });

        let line_regex = format!("^{}{}$", named_captures, REGEX_PARAM_SEQ);
        let regex = Regex::new(&line_regex).unwrap();
        Matcher::new(with_format, regex)
    }
}