From d9b89ccdacee83cc5d4f902b5130ffa6e0f2a057 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Mon, 23 Oct 2017 19:28:23 -0700 Subject: [PATCH] simplify RouteRecognizer reuse --- src/dev.rs | 21 ++------------------- src/recognizer.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 19 deletions(-) diff --git a/src/dev.rs b/src/dev.rs index f87dae74..7e269e97 100644 --- a/src/dev.rs +++ b/src/dev.rs @@ -7,26 +7,9 @@ //! # #![allow(unused_imports)] //! use actix_web::dev::*; //! ``` -pub use ws; -pub use httpcodes; -pub use error::ParseError; -pub use application::{Application, ApplicationBuilder, Middleware}; -pub use httprequest::HttpRequest; -pub use httpresponse::{Body, HttpResponse, HttpResponseBuilder}; -pub use payload::{Payload, PayloadItem, PayloadError}; -pub use resource::{Reply, Resource}; -pub use route::{Route, RouteFactory, RouteHandler}; -pub use recognizer::Params; -pub use logger::Logger; -pub use server::HttpServer; -pub use context::HttpContext; -pub use staticfiles::StaticFiles; -// re-exports -pub use http::{Method, StatusCode}; -pub use cookie::{Cookie, CookieBuilder}; -pub use cookie::{ParseError as CookieParseError}; -pub use http_range::{HttpRange, HttpRangeParseError}; +pub use super::*; // dev specific pub use task::Task; +pub use recognizer::RouteRecognizer; diff --git a/src/recognizer.rs b/src/recognizer.rs index c3296d74..2dcb75c3 100644 --- a/src/recognizer.rs +++ b/src/recognizer.rs @@ -1,4 +1,5 @@ use std::rc::Rc; +use std::string::ToString; use std::collections::HashMap; use regex::{Regex, RegexSet, Captures}; @@ -11,7 +12,19 @@ pub struct RouteRecognizer { routes: Vec<(Pattern, T)>, } +impl Default for RouteRecognizer { + + fn default() -> Self { + RouteRecognizer { + prefix: 0, + patterns: RegexSet::new([""].iter()).unwrap(), + routes: Vec::new(), + } + } +} + impl RouteRecognizer { + pub fn new(prefix: String, routes: Vec<(String, T)>) -> Self { let mut paths = Vec::new(); let mut handlers = Vec::new(); @@ -29,6 +42,22 @@ impl RouteRecognizer { } } + pub fn set_routes(&mut self, routes: Vec<(&str, T)>) { + let mut paths = Vec::new(); + let mut handlers = Vec::new(); + for item in routes { + let pat = parse(item.0); + handlers.push((Pattern::new(&pat), item.1)); + paths.push(pat); + }; + self.patterns = RegexSet::new(&paths).unwrap(); + self.routes = handlers; + } + + pub fn set_prefix(&mut self, prefix: P) { + self.prefix = prefix.to_string().len() - 1; + } + pub fn recognize(&self, path: &str) -> Option<(Option, &T)> { if let Some(idx) = self.patterns.matches(&path[self.prefix..]).into_iter().next() {