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<Vec<RouteSegment>, 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: Vec<RouteSegment> = 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 pub(crate) fn try_match_path_into(
356 &self,
357 path: &str,
358 params: &mut HashMapXxHash3_64<String, String>,
359 ) -> bool {
360 let trimmed: &str = path.strip_prefix(DEFAULT_HTTP_PATH).unwrap_or(path);
361 let route_segments: &[RouteSegment] = self.get_0().as_slice();
362 let route_segments_len: usize = route_segments.len();
363 if trimmed.is_empty() {
364 return route_segments_len == 0;
365 }
366 let is_tail_regex: bool = matches!(route_segments.last(), Some(RouteSegment::Regex(_, _)));
367 if !is_tail_regex {
368 let mut captured: [MaybeUninit<(&str, &str)>; 16] =
369 [const { MaybeUninit::uninit() }; 16];
370 let mut captured_len: usize = 0;
371 let mut overflow: Option<Vec<(&str, &str)>> = None;
372 let mut seg_idx: usize = 0;
373 for part in trimmed.split(DEFAULT_HTTP_PATH) {
374 if part.is_empty() {
375 return false;
376 }
377 let Some(expected) = route_segments.get(seg_idx) else {
378 return false;
379 };
380 match expected {
381 RouteSegment::Static(literal) => {
382 if part != literal.as_str() {
383 return false;
384 }
385 }
386 RouteSegment::Dynamic(param_name) => {
387 if captured_len < captured.len() {
388 captured[captured_len].write((param_name.as_str(), part));
389 captured_len += 1;
390 } else {
391 overflow
392 .get_or_insert_with(Vec::new)
393 .push((param_name.as_str(), part));
394 }
395 }
396 RouteSegment::Regex(param_name, regex) => {
397 if !regex.is_match(part) {
398 return false;
399 }
400 if captured_len < captured.len() {
401 captured[captured_len].write((param_name.as_str(), part));
402 captured_len += 1;
403 } else {
404 overflow
405 .get_or_insert_with(Vec::new)
406 .push((param_name.as_str(), part));
407 }
408 }
409 }
410 seg_idx += 1;
411 }
412 if seg_idx != route_segments_len {
413 return false;
414 }
415 if !params.is_empty() {
416 return_route_param_entries(params.drain());
417 }
418 if captured_len > 0 || overflow.is_some() {
419 ROUTE_PARAM_POOL.with(|pool: &RefCell<Vec<(String, String)>>| {
420 let mut pool: RefMut<'_, Vec<(String, String)>> = pool.borrow_mut();
421 for slot in &captured[..captured_len] {
422 let (param_name, part): (&str, &str) = unsafe { slot.assume_init() };
424 let (mut key, mut val): (String, String) = pool.pop().unwrap_or_default();
425 key.clear();
426 val.clear();
427 key.push_str(param_name);
428 val.push_str(part);
429 params.insert(key, val);
430 }
431 if let Some(extra) = overflow {
432 for (param_name, part) in extra {
433 let (mut key, mut val): (String, String) =
434 pool.pop().unwrap_or_default();
435 key.clear();
436 val.clear();
437 key.push_str(param_name);
438 val.push_str(part);
439 params.insert(key, val);
440 }
441 }
442 });
443 }
444 return true;
445 }
446 let prefix_len: usize = route_segments_len - 1;
447 let mut captured: [MaybeUninit<(&str, &str)>; 16] = [const { MaybeUninit::uninit() }; 16];
448 let mut captured_len: usize = 0;
449 let mut overflow: Option<Vec<(&str, &str)>> = None;
450 let sep_byte: u8 = DEFAULT_HTTP_PATH_BYTES[0];
451 let trimmed_bytes: &[u8] = trimmed.as_bytes();
452 let mut offset: usize = 0;
453 for expected in &route_segments[..prefix_len] {
454 if offset >= trimmed_bytes.len() {
455 return false;
456 }
457 let rel_end: usize = trimmed_bytes[offset..]
458 .iter()
459 .position(|byte: &u8| *byte == sep_byte)
460 .unwrap_or(trimmed_bytes.len() - offset);
461 let seg_end: usize = offset + rel_end;
462 let part: &str = &trimmed[offset..seg_end];
463 if part.is_empty() {
464 return false;
465 }
466 match expected {
467 RouteSegment::Static(literal) => {
468 if part != literal.as_str() {
469 return false;
470 }
471 }
472 RouteSegment::Dynamic(param_name) => {
473 if captured_len < captured.len() {
474 captured[captured_len].write((param_name.as_str(), part));
475 captured_len += 1;
476 } else {
477 overflow
478 .get_or_insert_with(Vec::new)
479 .push((param_name.as_str(), part));
480 }
481 }
482 RouteSegment::Regex(param_name, regex) => {
483 if !regex.is_match(part) {
484 return false;
485 }
486 if captured_len < captured.len() {
487 captured[captured_len].write((param_name.as_str(), part));
488 captured_len += 1;
489 } else {
490 overflow
491 .get_or_insert_with(Vec::new)
492 .push((param_name.as_str(), part));
493 }
494 }
495 }
496 offset = if seg_end < trimmed_bytes.len() {
497 seg_end + 1
498 } else {
499 trimmed_bytes.len()
500 };
501 }
502 let tail_slice: &str = if offset <= trimmed.len() {
503 &trimmed[offset..]
504 } else {
505 EMPTY_STR
506 };
507 let Some(RouteSegment::Regex(tail_name, tail_regex)) = route_segments.last() else {
508 return false;
509 };
510 if !tail_regex.is_match(tail_slice) {
511 return false;
512 }
513 if !params.is_empty() {
514 for pair in params.drain() {
515 return_route_param_entry(pair);
516 }
517 }
518 for slot in &captured[..captured_len] {
519 let (param_name, part): (&str, &str) = unsafe { slot.assume_init() };
521 let (mut key, mut val): (String, String) = take_route_param_entry();
522 key.push_str(param_name);
523 val.push_str(part);
524 params.insert(key, val);
525 }
526 if let Some(extra) = overflow {
527 for (param_name, part) in extra {
528 let (mut key, mut val): (String, String) = take_route_param_entry();
529 key.push_str(param_name);
530 val.push_str(part);
531 params.insert(key, val);
532 }
533 }
534 let (mut tail_key, mut tail_val): (String, String) = take_route_param_entry();
535 tail_key.push_str(tail_name.as_str());
536 tail_val.push_str(tail_slice);
537 params.insert(tail_key, tail_val);
538 true
539 }
540
541 #[inline(always)]
547 pub(crate) fn is_static(&self) -> bool {
548 self.get_0()
549 .iter()
550 .all(|segment: &RouteSegment| matches!(segment, RouteSegment::Static(_)))
551 }
552
553 #[inline(always)]
559 pub(crate) fn is_dynamic(&self) -> bool {
560 self.get_0()
561 .iter()
562 .any(|segment: &RouteSegment| matches!(segment, RouteSegment::Dynamic(_)))
563 && self
564 .get_0()
565 .iter()
566 .all(|segment: &RouteSegment| !matches!(segment, RouteSegment::Regex(_, _)))
567 }
568
569 #[inline(always)]
575 pub(crate) fn segment_count(&self) -> usize {
576 self.get_0().len()
577 }
578
579 #[inline(always)]
585 pub(crate) fn has_tail_regex(&self) -> bool {
586 matches!(self.get_0().last(), Some(RouteSegment::Regex(_, _)))
587 }
588}
589
590impl RouteMatcher {
595 #[inline(always)]
601 pub(crate) fn new() -> Self {
602 Self::default()
603 }
604
605 #[inline(always)]
615 fn count_path_segments(path: &str) -> usize {
616 let path: &str = path.strip_prefix(DEFAULT_HTTP_PATH).unwrap_or(path);
617 if path.is_empty() {
618 return 0;
619 }
620 let sep: u8 = DEFAULT_HTTP_PATH_BYTES[0];
621 let mut count: usize = 1;
622 for &byte in path.as_bytes() {
623 if byte == sep {
624 count += 1;
625 }
626 }
627 count
628 }
629
630 pub(crate) fn add(&mut self, pattern: &str, hook: ServerHookHandler) -> Result<(), RouteError> {
646 let route_pattern: RoutePattern = RoutePattern::new(pattern)?;
647 if route_pattern.is_static() {
648 if self.get_static_route().contains_key(pattern) {
649 return Err(RouteError::DuplicatePattern(pattern.to_owned()));
650 }
651 self.get_mut_static_route()
652 .insert(pattern.to_string(), hook);
653 return Ok(());
654 }
655 let target_map: &mut ServerHookPatternRoute = if route_pattern.is_dynamic() {
656 self.get_mut_dynamic_route()
657 } else {
658 self.get_mut_regex_route()
659 };
660 let segment_count: usize = route_pattern.segment_count();
661 let routes_for_count: &mut Vec<(RoutePattern, ServerHookHandler)> =
662 target_map.entry(segment_count).or_default();
663 match routes_for_count.binary_search_by(|entry: &(RoutePattern, ServerHookHandler)| {
664 entry.0.cmp(&route_pattern)
665 }) {
666 Ok(_) => return Err(RouteError::DuplicatePattern(pattern.to_owned())),
667 Err(pos) => routes_for_count.insert(pos, (route_pattern, hook)),
668 }
669 Ok(())
670 }
671
672 pub fn try_resolve_route<'a>(
689 &'a self,
690 ctx: &mut Context,
691 path: &str,
692 ) -> Option<&'a ServerHookHandler> {
693 if let Some(hook) = self.get_static_route().get(path) {
694 return Some(hook);
695 }
696 let path_segment_count: usize = Self::count_path_segments(path);
697 if let Some(routes) = self.get_dynamic_route().get(&path_segment_count) {
698 for (pattern, hook) in routes {
699 if pattern.try_match_path_into(path, ctx.get_mut_route_params()) {
700 return Some(hook);
701 }
702 }
703 }
704 if let Some(routes) = self.get_regex_route().get(&path_segment_count) {
705 for (pattern, hook) in routes {
706 if pattern.try_match_path_into(path, ctx.get_mut_route_params()) {
707 return Some(hook);
708 }
709 }
710 }
711 for (&segment_count, routes) in self.get_regex_route() {
712 if segment_count == path_segment_count || segment_count > path_segment_count + 1 {
713 continue;
714 }
715 for (pattern, hook) in routes {
716 if pattern.has_tail_regex()
717 && pattern.try_match_path_into(path, ctx.get_mut_route_params())
718 {
719 return Some(hook);
720 }
721 }
722 }
723 None
724 }
725}