use super::*;
collect!(HookType);
impl Default for RouteMatcher {
#[inline(always)]
fn default() -> Self {
Self {
static_route: hash_map_xx_hash3_64(),
dynamic_route: hash_map_xx_hash3_64(),
regex_route: hash_map_xx_hash3_64(),
}
}
}
impl PartialEq for RoutePattern {
#[inline(always)]
fn eq(&self, other: &Self) -> bool {
self.get_0() == other.get_0()
}
}
impl Eq for RoutePattern {}
impl Hash for RoutePattern {
#[inline(always)]
fn hash<H: Hasher>(&self, state: &mut H) {
self.get_0().hash(state);
}
}
impl PartialOrd for RoutePattern {
#[inline(always)]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for RoutePattern {
#[inline(always)]
fn cmp(&self, other: &Self) -> Ordering {
self.get_0().cmp(other.get_0())
}
}
impl PartialEq for RouteMatcher {
fn eq(&self, other: &Self) -> bool {
if self.get_static_route().len() != other.get_static_route().len() {
return false;
}
for key in self.get_static_route().keys() {
if !other.get_static_route().contains_key(key) {
return false;
}
}
if self.get_dynamic_route().len() != other.get_dynamic_route().len() {
return false;
}
for (segment_count, routes) in self.get_dynamic_route() {
match other.get_dynamic_route().get(segment_count) {
Some(other_routes) if routes.len() == other_routes.len() => {
for (pattern, _) in routes {
if !other_routes
.iter()
.any(|entry: &(RoutePattern, ServerHookHandler)| &entry.0 == pattern)
{
return false;
}
}
}
_ => return false,
}
}
if self.get_regex_route().len() != other.get_regex_route().len() {
return false;
}
for (segment_count, routes) in self.get_regex_route() {
match other.get_regex_route().get(segment_count) {
Some(other_routes) if routes.len() == other_routes.len() => {
for (pattern, _) in routes {
if !other_routes
.iter()
.any(|entry: &(RoutePattern, ServerHookHandler)| &entry.0 == pattern)
{
return false;
}
}
}
_ => return false,
}
}
true
}
}
impl Eq for RouteMatcher {}
impl Eq for RouteSegment {}
impl PartialOrd for RouteSegment {
#[inline(always)]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for RouteSegment {
#[inline(always)]
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(Self::Static(left_static), Self::Static(right_static)) => {
left_static.cmp(right_static)
}
(Self::Dynamic(left_dynamic), Self::Dynamic(right_dynamic)) => {
left_dynamic.cmp(right_dynamic)
}
(Self::Regex(left_name, left_regex), Self::Regex(right_name, right_regex)) => left_name
.cmp(right_name)
.then_with(|| left_regex.as_str().cmp(right_regex.as_str())),
(Self::Static(_), _) => Ordering::Less,
(_, Self::Static(_)) => Ordering::Greater,
(Self::Dynamic(_), _) => Ordering::Less,
(_, Self::Dynamic(_)) => Ordering::Greater,
}
}
}
impl PartialEq for RouteSegment {
#[inline(always)]
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Static(left_value), Self::Static(right_value)) => left_value == right_value,
(Self::Dynamic(left_value), Self::Dynamic(right_value)) => left_value == right_value,
(Self::Regex(left_name, left_regex), Self::Regex(right_name, right_regex)) => {
left_name == right_name && left_regex.as_str() == right_regex.as_str()
}
_ => false,
}
}
}
impl Hash for RouteSegment {
#[inline(always)]
fn hash<H: Hasher>(&self, state: &mut H) {
match self {
Self::Static(static_value) => {
0u8.hash(state);
static_value.hash(state);
}
Self::Dynamic(dynamic_value) => {
1u8.hash(state);
dynamic_value.hash(state);
}
Self::Regex(name, regex) => {
2u8.hash(state);
name.hash(state);
regex.as_str().hash(state);
}
}
}
}
impl RoutePattern {
pub(crate) fn new(route: &str) -> Result<RoutePattern, RouteError> {
Ok(Self(Self::parse_route(route)?))
}
fn parse_route(route: &str) -> Result<Vec<RouteSegment>, RouteError> {
if route.is_empty() {
return Err(RouteError::EmptyPattern);
}
let route: &str = route.strip_prefix(DEFAULT_HTTP_PATH).unwrap_or(route);
if route.is_empty() {
return Ok(Vec::new());
}
let estimated_segments: usize = route.matches(DEFAULT_HTTP_PATH).count() + 1;
let mut segments: Vec<RouteSegment> = Vec::with_capacity(estimated_segments);
for segment in route.split(DEFAULT_HTTP_PATH) {
if segment.starts_with(LEFT_BRACKET) && segment.ends_with(RIGHT_BRACKET) {
let content: &str = &segment[1..segment.len() - 1];
if let Some((name, pattern)) = content.split_once(COLON) {
let anchored: String = format!("\\A(?:{pattern})\\z");
match Regex::new(&anchored) {
Ok(regex) => {
segments.push(RouteSegment::Regex(name.to_owned(), regex));
}
Err(error) => {
return Err(RouteError::InvalidRegexPattern(format!(
"Invalid regex pattern '{}{}{}",
pattern, COLON, error
)));
}
}
} else {
segments.push(RouteSegment::Dynamic(content.to_owned()));
}
} else {
segments.push(RouteSegment::Static(segment.to_owned()));
}
}
Ok(segments)
}
pub(crate) fn try_match_path_into(
&self,
path: &str,
params: &mut HashMapXxHash3_64<String, String>,
) -> bool {
let trimmed: &str = path.strip_prefix(DEFAULT_HTTP_PATH).unwrap_or(path);
let route_segments: &[RouteSegment] = self.get_0().as_slice();
let route_segments_len: usize = route_segments.len();
if trimmed.is_empty() {
return route_segments_len == 0;
}
let is_tail_regex: bool = matches!(route_segments.last(), Some(RouteSegment::Regex(_, _)));
if !is_tail_regex {
let mut captured: [MaybeUninit<(&str, &str)>; 16] =
[const { MaybeUninit::uninit() }; 16];
let mut captured_len: usize = 0;
let mut overflow: Option<Vec<(&str, &str)>> = None;
let mut seg_idx: usize = 0;
for part in trimmed.split(DEFAULT_HTTP_PATH) {
if part.is_empty() {
return false;
}
let Some(expected) = route_segments.get(seg_idx) else {
return false;
};
match expected {
RouteSegment::Static(literal) => {
if part != literal.as_str() {
return false;
}
}
RouteSegment::Dynamic(param_name) => {
if captured_len < captured.len() {
captured[captured_len].write((param_name.as_str(), part));
captured_len += 1;
} else {
overflow
.get_or_insert_with(Vec::new)
.push((param_name.as_str(), part));
}
}
RouteSegment::Regex(param_name, regex) => {
if !regex.is_match(part) {
return false;
}
if captured_len < captured.len() {
captured[captured_len].write((param_name.as_str(), part));
captured_len += 1;
} else {
overflow
.get_or_insert_with(Vec::new)
.push((param_name.as_str(), part));
}
}
}
seg_idx += 1;
}
if seg_idx != route_segments_len {
return false;
}
if !params.is_empty() {
for pair in params.drain() {
return_route_param_entry(pair);
}
}
for slot in &captured[..captured_len] {
let (param_name, part): (&str, &str) = unsafe { slot.assume_init() };
let (mut key, mut val): (String, String) = take_route_param_entry();
key.push_str(param_name);
val.push_str(part);
params.insert(key, val);
}
if let Some(extra) = overflow {
for (param_name, part) in extra {
let (mut key, mut val): (String, String) = take_route_param_entry();
key.push_str(param_name);
val.push_str(part);
params.insert(key, val);
}
}
return true;
}
let prefix_len: usize = route_segments_len - 1;
let mut captured: [MaybeUninit<(&str, &str)>; 16] = [const { MaybeUninit::uninit() }; 16];
let mut captured_len: usize = 0;
let mut overflow: Option<Vec<(&str, &str)>> = None;
let sep_byte: u8 = DEFAULT_HTTP_PATH_BYTES[0];
let trimmed_bytes: &[u8] = trimmed.as_bytes();
let mut offset: usize = 0;
for expected in &route_segments[..prefix_len] {
if offset >= trimmed_bytes.len() {
return false;
}
let rel_end: usize = trimmed_bytes[offset..]
.iter()
.position(|byte: &u8| *byte == sep_byte)
.unwrap_or(trimmed_bytes.len() - offset);
let seg_end: usize = offset + rel_end;
let part: &str = &trimmed[offset..seg_end];
if part.is_empty() {
return false;
}
match expected {
RouteSegment::Static(literal) => {
if part != literal.as_str() {
return false;
}
}
RouteSegment::Dynamic(param_name) => {
if captured_len < captured.len() {
captured[captured_len].write((param_name.as_str(), part));
captured_len += 1;
} else {
overflow
.get_or_insert_with(Vec::new)
.push((param_name.as_str(), part));
}
}
RouteSegment::Regex(param_name, regex) => {
if !regex.is_match(part) {
return false;
}
if captured_len < captured.len() {
captured[captured_len].write((param_name.as_str(), part));
captured_len += 1;
} else {
overflow
.get_or_insert_with(Vec::new)
.push((param_name.as_str(), part));
}
}
}
offset = if seg_end < trimmed_bytes.len() {
seg_end + 1
} else {
trimmed_bytes.len()
};
}
let tail_slice: &str = if offset <= trimmed.len() {
&trimmed[offset..]
} else {
EMPTY_STR
};
let Some(RouteSegment::Regex(tail_name, tail_regex)) = route_segments.last() else {
return false;
};
if !tail_regex.is_match(tail_slice) {
return false;
}
if !params.is_empty() {
for pair in params.drain() {
return_route_param_entry(pair);
}
}
for slot in &captured[..captured_len] {
let (param_name, part): (&str, &str) = unsafe { slot.assume_init() };
let (mut key, mut val): (String, String) = take_route_param_entry();
key.push_str(param_name);
val.push_str(part);
params.insert(key, val);
}
if let Some(extra) = overflow {
for (param_name, part) in extra {
let (mut key, mut val): (String, String) = take_route_param_entry();
key.push_str(param_name);
val.push_str(part);
params.insert(key, val);
}
}
let (mut tail_key, mut tail_val): (String, String) = take_route_param_entry();
tail_key.push_str(tail_name.as_str());
tail_val.push_str(tail_slice);
params.insert(tail_key, tail_val);
true
}
#[inline(always)]
pub(crate) fn is_static(&self) -> bool {
self.get_0()
.iter()
.all(|segment: &RouteSegment| matches!(segment, RouteSegment::Static(_)))
}
#[inline(always)]
pub(crate) fn is_dynamic(&self) -> bool {
self.get_0()
.iter()
.any(|segment: &RouteSegment| matches!(segment, RouteSegment::Dynamic(_)))
&& self
.get_0()
.iter()
.all(|segment: &RouteSegment| !matches!(segment, RouteSegment::Regex(_, _)))
}
#[inline(always)]
pub(crate) fn segment_count(&self) -> usize {
self.get_0().len()
}
#[inline(always)]
pub(crate) fn has_tail_regex(&self) -> bool {
matches!(self.get_0().last(), Some(RouteSegment::Regex(_, _)))
}
}
impl RouteMatcher {
#[inline(always)]
pub(crate) fn new() -> Self {
Self::default()
}
#[inline(always)]
fn count_path_segments(path: &str) -> usize {
let path: &str = path.strip_prefix(DEFAULT_HTTP_PATH).unwrap_or(path);
if path.is_empty() {
return 0;
}
let sep: u8 = DEFAULT_HTTP_PATH_BYTES[0];
let mut count: usize = 1;
for &byte in path.as_bytes() {
if byte == sep {
count += 1;
}
}
count
}
pub(crate) fn add(&mut self, pattern: &str, hook: ServerHookHandler) -> Result<(), RouteError> {
let route_pattern: RoutePattern = RoutePattern::new(pattern)?;
if route_pattern.is_static() {
if self.get_static_route().contains_key(pattern) {
return Err(RouteError::DuplicatePattern(pattern.to_owned()));
}
self.get_mut_static_route()
.insert(pattern.to_string(), hook);
return Ok(());
}
let target_map: &mut ServerHookPatternRoute = if route_pattern.is_dynamic() {
self.get_mut_dynamic_route()
} else {
self.get_mut_regex_route()
};
let segment_count: usize = route_pattern.segment_count();
let routes_for_count: &mut Vec<(RoutePattern, ServerHookHandler)> =
target_map.entry(segment_count).or_default();
match routes_for_count.binary_search_by(|entry: &(RoutePattern, ServerHookHandler)| {
entry.0.cmp(&route_pattern)
}) {
Ok(_) => return Err(RouteError::DuplicatePattern(pattern.to_owned())),
Err(pos) => routes_for_count.insert(pos, (route_pattern, hook)),
}
Ok(())
}
pub fn try_resolve_route<'a>(
&'a self,
ctx: &mut Context,
path: &str,
) -> Option<&'a ServerHookHandler> {
if let Some(hook) = self.get_static_route().get(path) {
return Some(hook);
}
let path_segment_count: usize = Self::count_path_segments(path);
if let Some(routes) = self.get_dynamic_route().get(&path_segment_count) {
for (pattern, hook) in routes {
if pattern.try_match_path_into(path, ctx.get_mut_route_params()) {
return Some(hook);
}
}
}
if let Some(routes) = self.get_regex_route().get(&path_segment_count) {
for (pattern, hook) in routes {
if pattern.try_match_path_into(path, ctx.get_mut_route_params()) {
return Some(hook);
}
}
}
for (&segment_count, routes) in self.get_regex_route() {
if segment_count == path_segment_count || segment_count > path_segment_count + 1 {
continue;
}
for (pattern, hook) in routes {
if pattern.has_tail_regex()
&& pattern.try_match_path_into(path, ctx.get_mut_route_params())
{
return Some(hook);
}
}
}
None
}
}