1use std::collections::HashMap;
4
5use crate::{HttpError, Method, RouteCollection};
6
7pub const ROUTE_ATTRIBUTE: &str = "_route";
9
10#[derive(Clone, Debug, Eq, PartialEq)]
12pub struct MatchResult {
13 route_name: String,
14 parameters: HashMap<String, String>,
15}
16
17impl MatchResult {
18 #[must_use]
20 pub fn route_name(&self) -> &str {
21 &self.route_name
22 }
23
24 #[must_use]
26 pub const fn parameters(&self) -> &HashMap<String, String> {
27 &self.parameters
28 }
29}
30
31#[derive(Clone, Debug, Default)]
33pub struct UrlMatcher {
34 collection: RouteCollection,
35}
36
37impl UrlMatcher {
38 #[must_use]
40 pub const fn new(collection: RouteCollection) -> Self {
41 Self { collection }
42 }
43
44 #[must_use]
46 pub const fn collection(&self) -> &RouteCollection {
47 &self.collection
48 }
49
50 pub fn match_request(&self, method: Method, path: &str) -> Result<MatchResult, HttpError> {
57 let mut path_matched = false;
58 for route in self.collection.routes() {
59 let Some(parameters) = match_path(route.path(), path) else {
60 continue;
61 };
62 path_matched = true;
63 if route.allows(method) {
64 return Ok(MatchResult {
65 route_name: route.name().to_owned(),
66 parameters,
67 });
68 }
69 }
70 if path_matched {
71 Err(HttpError::status(
72 405,
73 format!("method `{method}` not allowed"),
74 ))
75 } else {
76 Err(HttpError::status(404, format!("no route for `{path}`")))
77 }
78 }
79
80 pub fn apply(&self, request: &mut crate::Request) -> Result<MatchResult, HttpError> {
86 let matched = self.match_request(request.method(), request.path())?;
87 request
88 .attributes_mut()
89 .insert(ROUTE_ATTRIBUTE, matched.route_name().to_owned());
90 for (key, value) in matched.parameters() {
91 request.attributes_mut().insert(key.clone(), value.clone());
92 }
93 Ok(matched)
94 }
95}
96
97fn match_path(pattern: &str, path: &str) -> Option<HashMap<String, String>> {
98 let pattern_segments = crate::route::split_segments(pattern);
99 let path_segments = crate::route::split_segments(path);
100 if pattern_segments.len() != path_segments.len() {
101 return None;
102 }
103 let mut parameters = HashMap::new();
104 for (expected, actual) in pattern_segments.into_iter().zip(path_segments) {
105 if let Some(name) = crate::route::parameter_name(expected) {
106 parameters.insert(name.to_owned(), actual.to_owned());
107 } else if expected != actual {
108 return None;
109 }
110 }
111 Some(parameters)
112}