1use super::*;
2
3collect!(HookType);
5
6impl Default for RouteMatcher {
8 #[inline(always)]
14 fn default() -> Self {
15 Self {
16 static_route: hash_map_xx_hash3_64(),
17 dynamic_route: hash_map_xx_hash3_64(),
18 regex_route: hash_map_xx_hash3_64(),
19 }
20 }
21}
22
23impl PartialEq for RoutePattern {
27 #[inline(always)]
37 fn eq(&self, other: &Self) -> bool {
38 self.get_0() == other.get_0()
39 }
40}
41
42impl Eq for RoutePattern {}
46
47impl Hash for RoutePattern {
51 #[inline(always)]
57 fn hash<H: Hasher>(&self, state: &mut H) {
58 self.get_0().hash(state);
59 }
60}
61
62impl PartialOrd for RoutePattern {
66 #[inline(always)]
76 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
77 Some(self.cmp(other))
78 }
79}
80
81impl Ord for RoutePattern {
85 #[inline(always)]
95 fn cmp(&self, other: &Self) -> Ordering {
96 self.get_0().cmp(other.get_0())
97 }
98}
99
100impl PartialEq for RouteMatcher {
104 fn eq(&self, other: &Self) -> bool {
114 if self.get_static_route().len() != other.get_static_route().len() {
115 return false;
116 }
117 for key in self.get_static_route().keys() {
118 if !other.get_static_route().contains_key(key) {
119 return false;
120 }
121 }
122 if self.get_dynamic_route().len() != other.get_dynamic_route().len() {
123 return false;
124 }
125 for (segment_count, routes) in self.get_dynamic_route() {
126 match other.get_dynamic_route().get(segment_count) {
127 Some(other_routes) if routes.len() == other_routes.len() => {
128 for (pattern, _) in routes {
129 if !other_routes
130 .iter()
131 .any(|entry: &(RoutePattern, ServerHookHandler)| &entry.0 == pattern)
132 {
133 return false;
134 }
135 }
136 }
137 _ => return false,
138 }
139 }
140 if self.get_regex_route().len() != other.get_regex_route().len() {
141 return false;
142 }
143 for (segment_count, routes) in self.get_regex_route() {
144 match other.get_regex_route().get(segment_count) {
145 Some(other_routes) if routes.len() == other_routes.len() => {
146 for (pattern, _) in routes {
147 if !other_routes
148 .iter()
149 .any(|entry: &(RoutePattern, ServerHookHandler)| &entry.0 == pattern)
150 {
151 return false;
152 }
153 }
154 }
155 _ => return false,
156 }
157 }
158 true
159 }
160}
161
162impl Eq for RouteMatcher {}
166
167impl Eq for RouteSegment {}
171
172impl PartialOrd for RouteSegment {
176 #[inline(always)]
186 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
187 Some(self.cmp(other))
188 }
189}
190
191impl Ord for RouteSegment {
195 #[inline(always)]
205 fn cmp(&self, other: &Self) -> Ordering {
206 match (self, other) {
207 (Self::Static(left_static), Self::Static(right_static)) => {
208 left_static.cmp(right_static)
209 }
210 (Self::Dynamic(left_dynamic), Self::Dynamic(right_dynamic)) => {
211 left_dynamic.cmp(right_dynamic)
212 }
213 (Self::Regex(left_name, left_regex), Self::Regex(right_name, right_regex)) => left_name
214 .cmp(right_name)
215 .then_with(|| left_regex.as_str().cmp(right_regex.as_str())),
216 (Self::Static(_), _) => Ordering::Less,
217 (_, Self::Static(_)) => Ordering::Greater,
218 (Self::Dynamic(_), _) => Ordering::Less,
219 (_, Self::Dynamic(_)) => Ordering::Greater,
220 }
221 }
222}
223
224impl PartialEq for RouteSegment {
228 #[inline(always)]
238 fn eq(&self, other: &Self) -> bool {
239 match (self, other) {
240 (Self::Static(left_value), Self::Static(right_value)) => left_value == right_value,
241 (Self::Dynamic(left_value), Self::Dynamic(right_value)) => left_value == right_value,
242 (Self::Regex(left_name, left_regex), Self::Regex(right_name, right_regex)) => {
243 left_name == right_name && left_regex.as_str() == right_regex.as_str()
244 }
245 _ => false,
246 }
247 }
248}
249
250impl Hash for RouteSegment {
254 #[inline(always)]
260 fn hash<H: Hasher>(&self, state: &mut H) {
261 match self {
262 Self::Static(static_value) => {
263 0u8.hash(state);
264 static_value.hash(state);
265 }
266 Self::Dynamic(dynamic_value) => {
267 1u8.hash(state);
268 dynamic_value.hash(state);
269 }
270 Self::Regex(name, regex) => {
271 2u8.hash(state);
272 name.hash(state);
273 regex.as_str().hash(state);
274 }
275 }
276 }
277}
278
279impl RoutePattern {
284 pub(crate) fn new(route: &str) -> Result<RoutePattern, RouteError> {
294 Ok(Self(Self::parse_route(route)?))
295 }
296
297 fn parse_route(route: &str) -> Result<RouteSegmentList, RouteError> {
309 if route.is_empty() {
310 return Err(RouteError::EmptyPattern);
311 }
312 let route: &str = route.strip_prefix(DEFAULT_HTTP_PATH).unwrap_or(route);
313 if route.is_empty() {
314 return Ok(Vec::new());
315 }
316 let estimated_segments: usize = route.matches(DEFAULT_HTTP_PATH).count() + 1;
317 let mut segments: RouteSegmentList = Vec::with_capacity(estimated_segments);
318 for segment in route.split(DEFAULT_HTTP_PATH) {
319 if segment.starts_with(LEFT_BRACKET) && segment.ends_with(RIGHT_BRACKET) {
320 let content: &str = &segment[1..segment.len() - 1];
321 if let Some((name, pattern)) = content.split_once(COLON) {
322 let anchored: String = format!("\\A(?:{pattern})\\z");
323 match Regex::new(&anchored) {
324 Ok(regex) => {
325 segments.push(RouteSegment::Regex(name.to_owned(), regex));
326 }
327 Err(error) => {
328 return Err(RouteError::InvalidRegexPattern(format!(
329 "Invalid regex pattern '{}{}{}",
330 pattern, COLON, error
331 )));
332 }
333 }
334 } else {
335 segments.push(RouteSegment::Dynamic(content.to_owned()));
336 }
337 } else {
338 segments.push(RouteSegment::Static(segment.to_owned()));
339 }
340 }
341 Ok(segments)
342 }
343
344 fn try_match_static_path(&self, path: &str) -> Option<RouteParams> {
361 let route_segments_len: usize = self.get_0().len();
362 let path_bytes: &[u8] = path.as_bytes();
363 let path_separator_byte: u8 = DEFAULT_HTTP_PATH_BYTES[0];
364 let mut segment_start: usize = 0;
365 let mut matched_segments: usize = 0;
366 let mut saw_content: bool = false;
367 for (byte_index, ¤t_byte) in path_bytes.iter().enumerate() {
368 if current_byte == path_separator_byte {
369 saw_content = true;
370 let expected: &str = match self.get_0().get(matched_segments) {
371 Some(RouteSegment::Static(s)) => s.as_str(),
372 Some(_) => return None,
373 None => return None,
374 };
375 if &path[segment_start..byte_index] != expected {
376 return None;
377 }
378 matched_segments += 1;
379 segment_start = byte_index + 1;
380 }
381 }
382 if segment_start < path.len() {
383 saw_content = true;
384 let expected: &str = match self.get_0().get(matched_segments) {
385 Some(RouteSegment::Static(s)) => s.as_str(),
386 Some(_) => return None,
387 None => return None,
388 };
389 if &path[segment_start..] != expected {
390 return None;
391 }
392 matched_segments += 1;
393 }
394 let all_matched: bool = matched_segments == route_segments_len;
395 let empty_single_match: bool = !saw_content && route_segments_len == 1 && path.is_empty();
396 if all_matched || empty_single_match {
397 Some(hash_map_xx_hash3_64())
398 } else {
399 None
400 }
401 }
402
403 pub(crate) fn try_match_path_into(&self, path: &str, params: &mut RouteParams) -> bool {
415 let trimmed: &str = path.strip_prefix(DEFAULT_HTTP_PATH).unwrap_or(path);
416 let route_segments: &[RouteSegment] = self.get_0().as_slice();
417 let route_segments_len: usize = route_segments.len();
418 if trimmed.is_empty() {
419 return route_segments_len == 0;
420 }
421 if self.is_static() {
422 return self.try_match_static_path(trimmed).is_some();
423 }
424 let is_tail_regex: bool = matches!(route_segments.last(), Some(RouteSegment::Regex(_, _)));
425 if !is_tail_regex {
426 let mut captured: [MaybeUninit<(&str, &str)>; 16] =
427 [const { MaybeUninit::uninit() }; 16];
428 let mut captured_len: usize = 0;
429 let mut overflow: Option<Vec<(&str, &str)>> = None;
430 let mut seg_idx: usize = 0;
431 for part in trimmed.split(DEFAULT_HTTP_PATH) {
432 if part.is_empty() {
433 return false;
434 }
435 let Some(expected) = route_segments.get(seg_idx) else {
436 return false;
437 };
438 match expected {
439 RouteSegment::Static(literal) => {
440 if part != literal.as_str() {
441 return false;
442 }
443 }
444 RouteSegment::Dynamic(param_name) => {
445 if captured_len < captured.len() {
446 captured[captured_len].write((param_name.as_str(), part));
447 captured_len += 1;
448 } else {
449 overflow
450 .get_or_insert_with(Vec::new)
451 .push((param_name.as_str(), part));
452 }
453 }
454 RouteSegment::Regex(param_name, regex) => {
455 if !regex.is_match(part) {
456 return false;
457 }
458 if captured_len < captured.len() {
459 captured[captured_len].write((param_name.as_str(), part));
460 captured_len += 1;
461 } else {
462 overflow
463 .get_or_insert_with(Vec::new)
464 .push((param_name.as_str(), part));
465 }
466 }
467 }
468 seg_idx += 1;
469 }
470 if seg_idx != route_segments_len {
471 return false;
472 }
473 if !params.is_empty() {
474 for pair in params.drain() {
475 return_route_param_entry(pair);
476 }
477 }
478 for slot in &captured[..captured_len] {
479 let (param_name, part): (&str, &str) = unsafe { slot.assume_init() };
481 let (mut key, mut val): (String, String) = take_route_param_entry();
482 key.push_str(param_name);
483 val.push_str(part);
484 params.insert(key, val);
485 }
486 if let Some(extra) = overflow {
487 for (param_name, part) in extra {
488 let (mut key, mut val): (String, String) = take_route_param_entry();
489 key.push_str(param_name);
490 val.push_str(part);
491 params.insert(key, val);
492 }
493 }
494 return true;
495 }
496 match self.try_match_path(path) {
497 Some(matched) => {
498 *params = matched;
499 true
500 }
501 None => false,
502 }
503 }
504
505 pub(crate) fn try_match_path(&self, path: &str) -> Option<RouteParams> {
517 let path: &str = path.strip_prefix(DEFAULT_HTTP_PATH).unwrap_or(path);
518 let route_segments_len: usize = self.get_0().len();
519 let is_tail_regex: bool = matches!(self.get_0().last(), Some(RouteSegment::Regex(_, _)));
520 if path.is_empty() {
521 if route_segments_len == 0 {
522 return Some(hash_map_xx_hash3_64());
523 }
524 return None;
525 }
526 if self.is_static() {
527 return self.try_match_static_path(path);
528 }
529 let mut path_segments: PathComponentList = Vec::with_capacity(route_segments_len);
530 for segment in path.split(DEFAULT_HTTP_PATH) {
531 if segment.is_empty() {
532 if !is_tail_regex {
533 return None;
534 }
535 if path_segments.len() < route_segments_len - 1 {
536 return None;
537 }
538 }
539 path_segments.push(segment);
540 }
541 let path_segments_len: usize = path_segments.len();
542 if (!is_tail_regex && path_segments_len != route_segments_len)
543 || (is_tail_regex && path_segments_len < route_segments_len - 1)
544 {
545 return None;
546 }
547 let mut params: RouteParams = hash_map_xx_hash3_64();
548 for (idx, segment) in self.get_0().iter().enumerate() {
549 match segment {
550 RouteSegment::Static(expected_path) => {
551 if path_segments.get(idx).copied() != Some(expected_path.as_str()) {
552 return None;
553 }
554 }
555 RouteSegment::Dynamic(param_name) => {
556 let val: &str = path_segments.get(idx)?;
557 if val.is_empty() {
558 return None;
559 }
560 params.insert(param_name.clone(), val.to_string());
561 }
562 RouteSegment::Regex(param_name, regex) => {
563 if idx == route_segments_len - 1 {
564 let segment_value: String = path_segments[idx..].join(DEFAULT_HTTP_PATH);
565 if !regex.is_match(&segment_value) {
566 return None;
567 }
568 params.insert(param_name.clone(), segment_value);
569 return Some(params);
570 }
571 let val: &str = path_segments.get(idx)?;
572 if !regex.is_match(val) {
573 return None;
574 }
575 params.insert(param_name.clone(), val.to_string());
576 }
577 }
578 }
579 Some(params)
580 }
581
582 #[inline(always)]
588 pub(crate) fn is_static(&self) -> bool {
589 self.get_0()
590 .iter()
591 .all(|segment: &RouteSegment| matches!(segment, RouteSegment::Static(_)))
592 }
593
594 #[inline(always)]
600 pub(crate) fn is_dynamic(&self) -> bool {
601 self.get_0()
602 .iter()
603 .any(|segment: &RouteSegment| matches!(segment, RouteSegment::Dynamic(_)))
604 && self
605 .get_0()
606 .iter()
607 .all(|segment: &RouteSegment| !matches!(segment, RouteSegment::Regex(_, _)))
608 }
609
610 #[inline(always)]
616 pub(crate) fn segment_count(&self) -> usize {
617 self.get_0().len()
618 }
619
620 #[inline(always)]
626 pub(crate) fn has_tail_regex(&self) -> bool {
627 matches!(self.get_0().last(), Some(RouteSegment::Regex(_, _)))
628 }
629}
630
631impl RouteMatcher {
636 #[inline(always)]
642 pub(crate) fn new() -> Self {
643 Self::default()
644 }
645
646 #[inline(always)]
656 fn count_path_segments(path: &str) -> usize {
657 let path: &str = path.strip_prefix(DEFAULT_HTTP_PATH).unwrap_or(path);
658 if path.is_empty() {
659 return 0;
660 }
661 let sep: u8 = DEFAULT_HTTP_PATH_BYTES[0];
662 let mut count: usize = 1;
663 for &byte in path.as_bytes() {
664 if byte == sep {
665 count += 1;
666 }
667 }
668 count
669 }
670
671 pub(crate) fn add(&mut self, pattern: &str, hook: ServerHookHandler) -> Result<(), RouteError> {
687 let route_pattern: RoutePattern = RoutePattern::new(pattern)?;
688 if route_pattern.is_static() {
689 if self.get_static_route().contains_key(pattern) {
690 return Err(RouteError::DuplicatePattern(pattern.to_owned()));
691 }
692 self.get_mut_static_route()
693 .insert(pattern.to_string(), hook);
694 return Ok(());
695 }
696 let target_map: &mut ServerHookPatternRoute = if route_pattern.is_dynamic() {
697 self.get_mut_dynamic_route()
698 } else {
699 self.get_mut_regex_route()
700 };
701 let segment_count: usize = route_pattern.segment_count();
702 let routes_for_count: &mut Vec<(RoutePattern, ServerHookHandler)> =
703 target_map.entry(segment_count).or_default();
704 match routes_for_count.binary_search_by(|entry: &(RoutePattern, ServerHookHandler)| {
705 entry.0.cmp(&route_pattern)
706 }) {
707 Ok(_) => return Err(RouteError::DuplicatePattern(pattern.to_owned())),
708 Err(pos) => routes_for_count.insert(pos, (route_pattern, hook)),
709 }
710 Ok(())
711 }
712
713 pub fn try_resolve_route<'a>(
730 &'a self,
731 ctx: &mut Context,
732 path: &str,
733 ) -> Option<&'a ServerHookHandler> {
734 if let Some(hook) = self.get_static_route().get(path) {
735 return Some(hook);
736 }
737 let path_segment_count: usize = Self::count_path_segments(path);
738 if let Some(routes) = self.get_dynamic_route().get(&path_segment_count) {
739 for (pattern, hook) in routes {
740 if pattern.try_match_path_into(path, ctx.get_mut_route_params()) {
741 return Some(hook);
742 }
743 }
744 }
745 if let Some(routes) = self.get_regex_route().get(&path_segment_count) {
746 for (pattern, hook) in routes {
747 if pattern.try_match_path_into(path, ctx.get_mut_route_params()) {
748 return Some(hook);
749 }
750 }
751 }
752 for (&segment_count, routes) in self.get_regex_route() {
753 if segment_count == path_segment_count || segment_count > path_segment_count + 1 {
754 continue;
755 }
756 for (pattern, hook) in routes {
757 if pattern.has_tail_regex()
758 && pattern.try_match_path_into(path, ctx.get_mut_route_params())
759 {
760 return Some(hook);
761 }
762 }
763 }
764 None
765 }
766}