1
0
mirror of https://github.com/fafhrd91/actix-net synced 2025-01-19 15:24:39 +01:00
actix-net/actix-router/src/resource.rs

792 lines
26 KiB
Rust
Raw Normal View History

2019-01-05 13:19:25 -08:00
use std::cmp::min;
use std::collections::HashMap;
2019-01-05 13:19:25 -08:00
use std::hash::{Hash, Hasher};
2021-06-04 20:46:40 -04:00
use std::mem;
2019-01-05 13:19:25 -08:00
2019-12-25 15:10:01 +04:00
use regex::{escape, Regex, RegexSet};
2019-01-05 13:19:25 -08:00
use crate::path::{Path, PathItem};
use crate::{IntoPattern, Resource, ResourcePath};
2019-01-05 13:19:25 -08:00
const MAX_DYNAMIC_SEGMENTS: usize = 16;
/// Regex flags to allow '.' in regex to match '\n'
///
/// See the docs under: https://docs.rs/regex/1.5.4/regex/#grouping-and-flags
const REGEX_FLAGS: &str = "(?s-m)";
2019-02-09 07:24:35 -08:00
/// ResourceDef describes an entry in resources table
2019-01-05 13:19:25 -08:00
///
2019-02-09 07:24:35 -08:00
/// Resource definition can contain only 16 dynamic segments
2019-01-05 13:19:25 -08:00
#[derive(Clone, Debug)]
2019-02-09 07:24:35 -08:00
pub struct ResourceDef {
2019-03-08 12:33:44 -08:00
id: u16,
2019-01-05 13:19:25 -08:00
tp: PatternType,
2019-02-09 07:24:35 -08:00
name: String,
2019-01-05 13:19:25 -08:00
pattern: String,
2021-07-15 17:09:01 +03:00
elements: Option<Vec<PatternElement>>,
2019-01-05 13:19:25 -08:00
}
#[derive(Debug, Clone, PartialEq)]
enum PatternElement {
2021-07-15 17:09:01 +03:00
Const(String),
2019-01-05 13:19:25 -08:00
Var(String),
}
#[derive(Clone, Debug)]
2021-02-03 10:25:31 +00:00
#[allow(clippy::large_enum_variant)]
2019-01-05 13:19:25 -08:00
enum PatternType {
Static(String),
Prefix(String),
2021-07-15 17:09:01 +03:00
Dynamic(Regex, Vec<&'static str>),
DynamicSet(RegexSet, Vec<(Regex, Vec<&'static str>)>),
2019-01-05 13:19:25 -08:00
}
2019-02-09 07:24:35 -08:00
impl ResourceDef {
2019-01-05 13:19:25 -08:00
/// Parse path pattern and create new `Pattern` instance.
///
2019-12-25 15:10:01 +04:00
/// Panics if path pattern is malformed.
2019-12-25 19:54:20 +04:00
pub fn new<T: IntoPattern>(path: T) -> Self {
2019-12-25 15:34:21 +04:00
if path.is_single() {
let patterns = path.patterns();
ResourceDef::with_prefix(&patterns[0], false)
} else {
2019-12-25 19:54:20 +04:00
let set = path.patterns();
2019-12-25 15:34:21 +04:00
let mut data = Vec::new();
let mut re_set = Vec::new();
2019-12-25 15:10:01 +04:00
2019-12-25 15:34:21 +04:00
for path in set {
2021-07-15 17:09:01 +03:00
let (pattern, _, _) = ResourceDef::parse(&path, false);
2019-12-25 15:10:01 +04:00
2019-12-25 15:34:21 +04:00
let re = match Regex::new(&pattern) {
Ok(re) => re,
Err(err) => panic!("Wrong path pattern: \"{}\" {}", path, err),
};
// actix creates one router per thread
let names: Vec<_> = re
.capture_names()
2019-12-31 12:04:35 +06:00
.filter_map(|name| {
name.map(|name| Box::leak(Box::new(name.to_owned())).as_str())
})
2019-12-25 15:34:21 +04:00
.collect();
2021-07-15 17:09:01 +03:00
data.push((re, names));
2019-12-25 15:34:21 +04:00
re_set.push(pattern);
}
2019-12-25 15:10:01 +04:00
2019-12-25 15:34:21 +04:00
ResourceDef {
id: 0,
tp: PatternType::DynamicSet(RegexSet::new(re_set).unwrap(), data),
2021-07-15 17:09:01 +03:00
elements: None,
2019-12-25 15:34:21 +04:00
name: String::new(),
pattern: "".to_owned(),
}
2019-12-25 15:10:01 +04:00
}
}
2019-01-05 13:19:25 -08:00
/// Parse path pattern and create new `Pattern` instance.
///
/// Use `prefix` type instead of `static`.
///
2019-12-25 15:10:01 +04:00
/// Panics if path regex pattern is malformed.
2019-01-05 13:19:25 -08:00
pub fn prefix(path: &str) -> Self {
2019-02-09 07:24:35 -08:00
ResourceDef::with_prefix(path, true)
}
/// Parse path pattern and create new `Pattern` instance.
/// Inserts `/` to begging of the pattern.
///
///
/// Use `prefix` type instead of `static`.
///
2019-12-25 15:10:01 +04:00
/// Panics if path regex pattern is malformed.
pub fn root_prefix(path: &str) -> Self {
ResourceDef::with_prefix(&insert_slash(path), true)
}
2019-03-08 12:33:44 -08:00
/// Resource id
pub fn id(&self) -> u16 {
self.id
}
/// Set resource id
pub fn set_id(&mut self, id: u16) {
self.id = id;
2019-01-05 13:19:25 -08:00
}
/// Parse path pattern and create new `Pattern` instance with custom prefix
fn with_prefix(path: &str, for_prefix: bool) -> Self {
let path = path.to_owned();
2021-07-15 17:09:01 +03:00
let (pattern, elements, is_dynamic) = ResourceDef::parse(&path, for_prefix);
2019-01-05 13:19:25 -08:00
let tp = if is_dynamic {
let re = match Regex::new(&pattern) {
Ok(re) => re,
Err(err) => panic!("Wrong path pattern: \"{}\" {}", path, err),
};
// actix creates one router per thread
let names = re
.capture_names()
2019-12-31 12:04:35 +06:00
.filter_map(|name| {
name.map(|name| Box::leak(Box::new(name.to_owned())).as_str())
})
2019-01-05 13:19:25 -08:00
.collect();
2021-07-15 17:09:01 +03:00
PatternType::Dynamic(re, names)
2019-01-05 13:19:25 -08:00
} else if for_prefix {
PatternType::Prefix(pattern)
2019-01-05 13:19:25 -08:00
} else {
PatternType::Static(pattern)
2019-01-05 13:19:25 -08:00
};
2019-02-09 07:24:35 -08:00
ResourceDef {
2019-01-05 13:19:25 -08:00
tp,
2021-07-15 17:09:01 +03:00
elements: Some(elements),
2019-03-08 12:33:44 -08:00
id: 0,
2019-02-09 07:24:35 -08:00
name: String::new(),
pattern: path,
2019-01-05 13:19:25 -08:00
}
}
2019-03-08 12:33:44 -08:00
/// Resource pattern name
pub fn name(&self) -> &str {
&self.name
}
/// Mutable reference to a name of a resource definition.
pub fn name_mut(&mut self) -> &mut String {
&mut self.name
}
2019-01-05 13:19:25 -08:00
/// Path pattern of the resource
pub fn pattern(&self) -> &str {
&self.pattern
}
2020-09-21 22:46:59 +01:00
/// Check if path matches this pattern.
2021-01-26 09:45:43 +00:00
#[inline]
2019-01-05 13:19:25 -08:00
pub fn is_match(&self, path: &str) -> bool {
match self.tp {
PatternType::Static(ref s) => s == path,
PatternType::Prefix(ref s) => path.starts_with(s),
2021-07-15 17:09:01 +03:00
PatternType::Dynamic(ref re, _) => re.is_match(path),
2019-12-25 15:10:01 +04:00
PatternType::DynamicSet(ref re, _) => re.is_match(path),
2019-01-05 13:19:25 -08:00
}
}
2020-09-21 22:46:59 +01:00
/// Is prefix path a match against this resource.
pub fn is_prefix_match(&self, path: &str) -> Option<usize> {
let p_len = path.len();
let path = if path.is_empty() { "/" } else { path };
match self.tp {
PatternType::Static(ref s) => {
if s == path {
Some(p_len)
} else {
None
}
}
2021-07-15 17:09:01 +03:00
PatternType::Dynamic(ref re, _) => re.find(path).map(|m| m.end()),
PatternType::Prefix(ref s) => {
let len = if path == s {
s.len()
} else if path.starts_with(s)
&& (s.ends_with('/') || path.split_at(s.len()).1.starts_with('/'))
{
if s.ends_with('/') {
s.len() - 1
} else {
s.len()
}
} else {
return None;
};
Some(min(p_len, len))
}
2019-12-25 15:10:01 +04:00
PatternType::DynamicSet(ref re, ref params) => {
2021-07-15 17:09:01 +03:00
let idx = re.matches(path).into_iter().next()?;
let (ref pattern, _) = params[idx];
pattern.find(path).map(|m| m.end())
2019-12-25 15:10:01 +04:00
}
}
}
2020-09-21 22:46:59 +01:00
/// Is the given path and parameters a match against this pattern.
pub fn match_path<T: ResourcePath>(&self, path: &mut Path<T>) -> bool {
2021-07-15 17:09:01 +03:00
self.match_path_checked(path, &|_, _| true, &Some(()))
2019-01-05 13:19:25 -08:00
}
2019-05-15 10:21:29 -07:00
/// Is the given path and parameters a match against this pattern?
pub fn match_path_checked<R, T, F, U>(
&self,
res: &mut R,
check: &F,
user_data: &Option<U>,
) -> bool
where
T: ResourcePath,
R: Resource<T>,
F: Fn(&R, &Option<U>) -> bool,
{
2021-07-15 17:09:01 +03:00
let mut segments: [PathItem; MAX_DYNAMIC_SEGMENTS] = Default::default();
let path = res.resource_path();
let (matched_len, matched_vars) = match self.tp {
2019-05-15 10:21:29 -07:00
PatternType::Static(ref s) => {
2021-07-15 17:09:01 +03:00
if s != path.path() {
return false;
2019-05-15 10:21:29 -07:00
}
2021-07-15 17:09:01 +03:00
(path.len(), None)
2019-05-15 10:21:29 -07:00
}
2019-12-25 15:10:01 +04:00
PatternType::Prefix(ref s) => {
let len = {
2021-07-15 17:09:01 +03:00
let r_path = path.path();
if s == r_path {
2019-12-25 15:10:01 +04:00
s.len()
} else if r_path.starts_with(s)
&& (s.ends_with('/') || r_path.split_at(s.len()).1.starts_with('/'))
2019-12-25 15:10:01 +04:00
{
if s.ends_with('/') {
s.len() - 1
} else {
s.len()
}
} else {
return false;
}
};
2021-07-15 17:09:01 +03:00
(min(path.len(), len), None)
2019-12-25 15:10:01 +04:00
}
2021-07-15 17:09:01 +03:00
PatternType::Dynamic(ref re, ref names) => {
let captures = match re.captures(path.path()) {
Some(captures) => captures,
_ => return false,
};
for (no, name) in names.iter().enumerate() {
if let Some(m) = captures.name(&name) {
segments[no] = PathItem::Segment(m.start() as u16, m.end() as u16);
} else {
log::error!("Dynamic path match but not all segments found: {}", name);
return false;
2019-05-15 10:21:29 -07:00
}
}
2021-07-15 17:09:01 +03:00
(captures[0].len(), Some(names))
2019-05-15 10:21:29 -07:00
}
2019-12-25 15:10:01 +04:00
PatternType::DynamicSet(ref re, ref params) => {
2021-07-15 17:09:01 +03:00
let path = path.path();
let (pattern, names) = match re.matches(path).into_iter().next() {
Some(idx) => &params[idx],
_ => return false,
};
let captures = match pattern.captures(path.path()) {
Some(captures) => captures,
_ => return false,
};
for (no, name) in names.iter().enumerate() {
if let Some(m) = captures.name(&name) {
segments[no] = PathItem::Segment(m.start() as u16, m.end() as u16);
2019-05-15 10:21:29 -07:00
} else {
2021-07-15 17:09:01 +03:00
log::error!("Dynamic path match but not all segments found: {}", name);
2019-05-15 10:21:29 -07:00
return false;
}
2021-07-15 17:09:01 +03:00
}
(captures[0].len(), Some(names))
}
};
2019-12-25 15:10:01 +04:00
2021-07-15 17:09:01 +03:00
if !check(res, user_data) {
return false;
}
2019-12-25 15:10:01 +04:00
2021-07-15 17:09:01 +03:00
// Modify `path` to skip matched part and store matched segments
let path = res.resource_path();
if let Some(vars) = matched_vars {
for i in 0..vars.len() {
path.add(vars[i], mem::take(&mut segments[i]));
2019-05-15 10:21:29 -07:00
}
}
2021-07-15 17:09:01 +03:00
path.skip(matched_len as u16);
true
2019-05-15 10:21:29 -07:00
}
2021-07-15 17:09:01 +03:00
/// Build resource path with a closure that maps variable elements' names to values.
fn build_resource_path<F, I>(&self, path: &mut String, mut vars: F) -> bool
where
2021-07-15 17:09:01 +03:00
F: FnMut(&str) -> Option<I>,
I: AsRef<str>,
{
2021-07-15 17:09:01 +03:00
for el in match self.elements {
Some(ref elements) => elements,
None => return false,
} {
match *el {
PatternElement::Const(ref val) => path.push_str(val),
PatternElement::Var(ref name) => match vars(name) {
Some(val) => path.push_str(val.as_ref()),
_ => return false,
},
2019-12-25 15:10:01 +04:00
}
}
true
}
2019-01-05 13:19:25 -08:00
2021-07-15 17:09:01 +03:00
/// Build resource path from elements. Returns `true` on success.
pub fn resource_path<U, I>(&self, path: &mut String, elements: &mut U) -> bool
where
U: Iterator<Item = I>,
I: AsRef<str>,
{
self.build_resource_path(path, |_| elements.next())
}
/// Build resource path from elements. Returns `true` on success.
pub fn resource_path_named<K, V, S>(
&self,
path: &mut String,
elements: &HashMap<K, V, S>,
) -> bool
where
K: std::borrow::Borrow<str> + Eq + Hash,
V: AsRef<str>,
S: std::hash::BuildHasher,
{
2021-07-15 17:09:01 +03:00
self.build_resource_path(path, |name| elements.get(name))
}
2019-04-22 21:19:22 -07:00
fn parse_param(pattern: &str) -> (PatternElement, String, &str, bool) {
2019-01-05 13:19:25 -08:00
const DEFAULT_PATTERN: &str = "[^/]+";
2019-04-22 21:19:22 -07:00
const DEFAULT_PATTERN_TAIL: &str = ".*";
2019-01-05 13:19:25 -08:00
let mut params_nesting = 0usize;
let close_idx = pattern
.find(|c| match c {
'{' => {
params_nesting += 1;
false
}
'}' => {
params_nesting -= 1;
params_nesting == 0
}
_ => false,
})
.expect("malformed dynamic segment");
2019-04-22 21:19:22 -07:00
let (mut param, mut rem) = pattern.split_at(close_idx + 1);
2019-01-05 13:19:25 -08:00
param = &param[1..param.len() - 1]; // Remove outer brackets
2019-04-22 21:19:22 -07:00
let tail = rem == "*";
2019-01-05 13:19:25 -08:00
let (name, pattern) = match param.find(':') {
Some(idx) => {
2019-04-22 21:19:22 -07:00
if tail {
panic!("Custom regex is not supported for remainder match");
}
2019-01-05 13:19:25 -08:00
let (name, pattern) = param.split_at(idx);
(name, &pattern[1..])
}
2019-04-22 21:19:22 -07:00
None => (
param,
if tail {
rem = &rem[1..];
DEFAULT_PATTERN_TAIL
} else {
DEFAULT_PATTERN
},
),
2019-01-05 13:19:25 -08:00
};
(
PatternElement::Var(name.to_string()),
format!(r"(?P<{}>{})", &name, &pattern),
rem,
2019-04-22 21:19:22 -07:00
tail,
2019-01-05 13:19:25 -08:00
)
}
2021-07-15 17:09:01 +03:00
fn parse(mut pattern: &str, mut for_prefix: bool) -> (String, Vec<PatternElement>, bool) {
2019-01-05 13:19:25 -08:00
if pattern.find('{').is_none() {
2021-04-16 02:06:11 +01:00
return if let Some(path) = pattern.strip_suffix('*') {
let re = format!("{}^{}(.*)", REGEX_FLAGS, path);
2021-07-15 17:09:01 +03:00
(re, vec![PatternElement::Const(String::from(path))], true)
2019-04-22 21:19:22 -07:00
} else {
(
String::from(pattern),
2021-07-15 17:09:01 +03:00
vec![PatternElement::Const(String::from(pattern))],
2019-04-22 21:19:22 -07:00
false,
)
};
}
2019-01-05 13:19:25 -08:00
let mut elements = Vec::new();
let mut re = format!("{}^", REGEX_FLAGS);
let mut dyn_elements = 0;
2019-01-05 13:19:25 -08:00
while let Some(idx) = pattern.find('{') {
let (prefix, rem) = pattern.split_at(idx);
2021-07-15 17:09:01 +03:00
elements.push(PatternElement::Const(String::from(prefix)));
2019-01-05 13:19:25 -08:00
re.push_str(&escape(prefix));
2019-04-22 21:19:22 -07:00
let (param_pattern, re_part, rem, tail) = Self::parse_param(rem);
if tail {
for_prefix = true;
}
elements.push(param_pattern);
2019-01-05 13:19:25 -08:00
re.push_str(&re_part);
pattern = rem;
dyn_elements += 1;
2019-01-05 13:19:25 -08:00
}
2021-07-15 17:09:01 +03:00
elements.push(PatternElement::Const(String::from(pattern)));
2019-01-05 13:19:25 -08:00
re.push_str(&escape(pattern));
if dyn_elements > MAX_DYNAMIC_SEGMENTS {
2019-01-05 13:19:25 -08:00
panic!(
"Only {} dynamic segments are allowed, provided: {}",
MAX_DYNAMIC_SEGMENTS, dyn_elements
2019-01-05 13:19:25 -08:00
);
}
if !for_prefix {
2020-09-06 17:41:42 +08:00
re.push('$');
2019-01-05 13:19:25 -08:00
}
2021-07-15 17:09:01 +03:00
(re, elements, true)
2019-01-05 13:19:25 -08:00
}
}
2019-02-09 07:24:35 -08:00
impl Eq for ResourceDef {}
impl PartialEq for ResourceDef {
fn eq(&self, other: &ResourceDef) -> bool {
2019-01-05 13:19:25 -08:00
self.pattern == other.pattern
}
}
2019-02-09 07:24:35 -08:00
impl Hash for ResourceDef {
2019-01-05 13:19:25 -08:00
fn hash<H: Hasher>(&self, state: &mut H) {
self.pattern.hash(state);
}
}
2019-02-09 07:24:35 -08:00
impl<'a> From<&'a str> for ResourceDef {
fn from(path: &'a str) -> ResourceDef {
ResourceDef::new(path)
}
}
impl From<String> for ResourceDef {
fn from(path: String) -> ResourceDef {
2019-12-25 15:34:21 +04:00
ResourceDef::new(path)
2019-02-09 07:24:35 -08:00
}
}
pub(crate) fn insert_slash(path: &str) -> String {
let mut path = path.to_owned();
if !path.is_empty() && !path.starts_with('/') {
path.insert(0, '/');
};
path
}
2019-01-05 13:19:25 -08:00
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_static() {
2019-02-09 07:24:35 -08:00
let re = ResourceDef::new("/");
2019-01-05 13:19:25 -08:00
assert!(re.is_match("/"));
assert!(!re.is_match("/a"));
2019-02-09 07:24:35 -08:00
let re = ResourceDef::new("/name");
2019-01-05 13:19:25 -08:00
assert!(re.is_match("/name"));
assert!(!re.is_match("/name1"));
assert!(!re.is_match("/name/"));
assert!(!re.is_match("/name~"));
assert_eq!(re.is_prefix_match("/name"), Some(5));
assert_eq!(re.is_prefix_match("/name1"), None);
assert_eq!(re.is_prefix_match("/name/"), None);
assert_eq!(re.is_prefix_match("/name~"), None);
2019-02-09 07:24:35 -08:00
let re = ResourceDef::new("/name/");
2019-01-05 13:19:25 -08:00
assert!(re.is_match("/name/"));
assert!(!re.is_match("/name"));
assert!(!re.is_match("/name/gs"));
2019-02-09 07:24:35 -08:00
let re = ResourceDef::new("/user/profile");
2019-01-05 13:19:25 -08:00
assert!(re.is_match("/user/profile"));
assert!(!re.is_match("/user/profile/profile"));
}
#[test]
fn test_parse_param() {
2019-02-09 07:24:35 -08:00
let re = ResourceDef::new("/user/{id}");
2019-01-05 13:19:25 -08:00
assert!(re.is_match("/user/profile"));
assert!(re.is_match("/user/2345"));
assert!(!re.is_match("/user/2345/"));
assert!(!re.is_match("/user/2345/sdg"));
let mut path = Path::new("/user/profile");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "profile");
let mut path = Path::new("/user/1245125");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "1245125");
2019-02-09 07:24:35 -08:00
let re = ResourceDef::new("/v{version}/resource/{id}");
2019-01-05 13:19:25 -08:00
assert!(re.is_match("/v1/resource/320120"));
assert!(!re.is_match("/v/resource/1"));
assert!(!re.is_match("/resource"));
let mut path = Path::new("/v151/resource/adage32");
2019-01-05 13:19:25 -08:00
assert!(re.match_path(&mut path));
assert_eq!(path.get("version").unwrap(), "151");
assert_eq!(path.get("id").unwrap(), "adage32");
2019-01-05 13:19:25 -08:00
2019-02-09 07:24:35 -08:00
let re = ResourceDef::new("/{id:[[:digit:]]{6}}");
2019-01-05 13:19:25 -08:00
assert!(re.is_match("/012345"));
assert!(!re.is_match("/012"));
assert!(!re.is_match("/01234567"));
assert!(!re.is_match("/XXXXXX"));
let mut path = Path::new("/012345");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "012345");
}
2020-01-28 20:27:33 +09:00
#[allow(clippy::cognitive_complexity)]
2019-12-25 15:10:01 +04:00
#[test]
fn test_dynamic_set() {
2019-12-25 19:54:20 +04:00
let re = ResourceDef::new(vec![
2019-12-25 15:34:21 +04:00
"/user/{id}",
"/v{version}/resource/{id}",
"/{id:[[:digit:]]{6}}",
]);
2019-12-25 15:10:01 +04:00
assert!(re.is_match("/user/profile"));
assert!(re.is_match("/user/2345"));
assert!(!re.is_match("/user/2345/"));
assert!(!re.is_match("/user/2345/sdg"));
let mut path = Path::new("/user/profile");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "profile");
let mut path = Path::new("/user/1245125");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "1245125");
assert!(re.is_match("/v1/resource/320120"));
assert!(!re.is_match("/v/resource/1"));
assert!(!re.is_match("/resource"));
let mut path = Path::new("/v151/resource/adage32");
2019-12-25 15:10:01 +04:00
assert!(re.match_path(&mut path));
assert_eq!(path.get("version").unwrap(), "151");
assert_eq!(path.get("id").unwrap(), "adage32");
2019-12-25 15:10:01 +04:00
assert!(re.is_match("/012345"));
assert!(!re.is_match("/012"));
assert!(!re.is_match("/01234567"));
assert!(!re.is_match("/XXXXXX"));
let mut path = Path::new("/012345");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "012345");
2019-12-25 19:54:20 +04:00
let re = ResourceDef::new([
"/user/{id}",
"/v{version}/resource/{id}",
"/{id:[[:digit:]]{6}}",
]);
assert!(re.is_match("/user/profile"));
assert!(re.is_match("/user/2345"));
assert!(!re.is_match("/user/2345/"));
assert!(!re.is_match("/user/2345/sdg"));
let re = ResourceDef::new([
"/user/{id}".to_string(),
"/v{version}/resource/{id}".to_string(),
"/{id:[[:digit:]]{6}}".to_string(),
]);
assert!(re.is_match("/user/profile"));
assert!(re.is_match("/user/2345"));
assert!(!re.is_match("/user/2345/"));
assert!(!re.is_match("/user/2345/sdg"));
2019-12-25 15:10:01 +04:00
}
2019-04-22 21:19:22 -07:00
#[test]
fn test_parse_tail() {
let re = ResourceDef::new("/user/-{id}*");
let mut path = Path::new("/user/-profile");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "profile");
let mut path = Path::new("/user/-2345");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "2345");
let mut path = Path::new("/user/-2345/");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "2345/");
let mut path = Path::new("/user/-2345/sdg");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "2345/sdg");
}
#[test]
fn test_static_tail() {
let re = ResourceDef::new("/user*");
assert!(re.is_match("/user/profile"));
assert!(re.is_match("/user/2345"));
assert!(re.is_match("/user/2345/"));
assert!(re.is_match("/user/2345/sdg"));
let re = ResourceDef::new("/user/*");
assert!(re.is_match("/user/profile"));
assert!(re.is_match("/user/2345"));
assert!(re.is_match("/user/2345/"));
assert!(re.is_match("/user/2345/sdg"));
}
#[test]
fn test_newline() {
let re = ResourceDef::new("/user/a\nb");
assert!(re.is_match("/user/a\nb"));
assert!(!re.is_match("/user/a\nb/profile"));
let re = ResourceDef::new("/a{x}b/test/a{y}b");
let mut path = Path::new("/a\nb/test/a\nb");
assert!(re.match_path(&mut path));
assert_eq!(path.get("x").unwrap(), "\n");
assert_eq!(path.get("y").unwrap(), "\n");
let re = ResourceDef::new("/user/*");
assert!(re.is_match("/user/a\nb/"));
let re = ResourceDef::new("/user/{id}*");
let mut path = Path::new("/user/a\nb/a\nb");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "a\nb/a\nb");
let re = ResourceDef::new("/user/{id:.*}");
let mut path = Path::new("/user/a\nb/a\nb");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "a\nb/a\nb");
}
2021-02-24 09:48:41 +00:00
#[cfg(feature = "http")]
2019-02-01 13:25:56 -08:00
#[test]
fn test_parse_urlencoded_param() {
2021-02-24 09:48:41 +00:00
use std::convert::TryFrom;
2019-02-09 07:24:35 -08:00
let re = ResourceDef::new("/user/{id}/test");
2019-02-01 13:25:56 -08:00
let mut path = Path::new("/user/2345/test");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "2345");
let mut path = Path::new("/user/qwe%25/test");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "qwe%25");
2021-02-24 09:48:41 +00:00
let uri = http::Uri::try_from("/user/qwe%25/test").unwrap();
2019-02-01 13:25:56 -08:00
let mut path = Path::new(uri);
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "qwe%25");
}
2019-01-05 13:19:25 -08:00
#[test]
fn test_resource_prefix() {
2019-02-09 07:24:35 -08:00
let re = ResourceDef::prefix("/name");
2019-01-05 13:19:25 -08:00
assert!(re.is_match("/name"));
assert!(re.is_match("/name/"));
assert!(re.is_match("/name/test/test"));
assert!(re.is_match("/name1"));
assert!(re.is_match("/name~"));
assert_eq!(re.is_prefix_match("/name"), Some(5));
assert_eq!(re.is_prefix_match("/name/"), Some(5));
assert_eq!(re.is_prefix_match("/name/test/test"), Some(5));
assert_eq!(re.is_prefix_match("/name1"), None);
assert_eq!(re.is_prefix_match("/name~"), None);
2019-02-09 07:24:35 -08:00
let re = ResourceDef::prefix("/name/");
2019-01-05 13:19:25 -08:00
assert!(re.is_match("/name/"));
assert!(re.is_match("/name/gs"));
assert!(!re.is_match("/name"));
let re = ResourceDef::root_prefix("name/");
assert!(re.is_match("/name/"));
assert!(re.is_match("/name/gs"));
assert!(!re.is_match("/name"));
2019-01-05 13:19:25 -08:00
}
#[test]
2020-09-21 22:46:59 +01:00
fn test_resource_prefix_dynamic() {
2019-02-09 07:24:35 -08:00
let re = ResourceDef::prefix("/{name}/");
2019-01-05 13:19:25 -08:00
assert!(re.is_match("/name/"));
assert!(re.is_match("/name/gs"));
assert!(!re.is_match("/name"));
assert_eq!(re.is_prefix_match("/name/"), Some(6));
assert_eq!(re.is_prefix_match("/name/gs"), Some(6));
assert_eq!(re.is_prefix_match("/name"), None);
2019-01-05 13:19:25 -08:00
let mut path = Path::new("/test2/");
assert!(re.match_path(&mut path));
assert_eq!(&path["name"], "test2");
assert_eq!(&path[0], "test2");
let mut path = Path::new("/test2/subpath1/subpath2/index.html");
assert!(re.match_path(&mut path));
assert_eq!(&path["name"], "test2");
assert_eq!(&path[0], "test2");
}
#[test]
fn test_resource_path() {
let mut s = String::new();
let resource = ResourceDef::new("/user/{item1}/test");
2020-01-28 20:27:33 +09:00
assert!(resource.resource_path(&mut s, &mut (&["user1"]).iter()));
assert_eq!(s, "/user/user1/test");
let mut s = String::new();
let resource = ResourceDef::new("/user/{item1}/{item2}/test");
2020-01-28 20:27:33 +09:00
assert!(resource.resource_path(&mut s, &mut (&["item", "item2"]).iter()));
assert_eq!(s, "/user/item/item2/test");
let mut s = String::new();
let resource = ResourceDef::new("/user/{item1}/{item2}");
2020-01-28 20:27:33 +09:00
assert!(resource.resource_path(&mut s, &mut (&["item", "item2"]).iter()));
assert_eq!(s, "/user/item/item2");
let mut s = String::new();
let resource = ResourceDef::new("/user/{item1}/{item2}/");
2020-01-28 20:27:33 +09:00
assert!(resource.resource_path(&mut s, &mut (&["item", "item2"]).iter()));
assert_eq!(s, "/user/item/item2/");
let mut s = String::new();
2020-01-28 20:27:33 +09:00
assert!(!resource.resource_path(&mut s, &mut (&["item"]).iter()));
let mut s = String::new();
2020-01-28 20:27:33 +09:00
assert!(resource.resource_path(&mut s, &mut (&["item", "item2"]).iter()));
assert_eq!(s, "/user/item/item2/");
2020-01-28 20:27:33 +09:00
assert!(!resource.resource_path(&mut s, &mut (&["item"]).iter()));
let mut s = String::new();
assert!(resource.resource_path(&mut s, &mut vec!["item", "item2"].into_iter()));
assert_eq!(s, "/user/item/item2/");
let mut map = HashMap::new();
map.insert("item1", "item");
let mut s = String::new();
assert!(!resource.resource_path_named(&mut s, &map));
let mut s = String::new();
map.insert("item2", "item2");
assert!(resource.resource_path_named(&mut s, &map));
assert_eq!(s, "/user/item/item2/");
}
2019-01-05 13:19:25 -08:00
}