1use crate::r#match::{AllowedMethods, RouteLookup, RouteMatch};
53use fastapi_types::Method;
54use std::collections::HashMap;
55use std::fmt;
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
59pub enum Converter {
60 #[default]
62 Str,
63 Int,
65 Float,
67 Uuid,
69 Path,
73}
74
75#[derive(Debug, Clone, PartialEq)]
77pub enum ParamValue {
78 Str(String),
80 Int(i64),
82 Float(f64),
84 Uuid(String),
86 Path(String),
88}
89
90impl ParamValue {
91 #[must_use]
93 pub fn as_str(&self) -> &str {
94 match self {
95 Self::Str(s) | Self::Uuid(s) | Self::Path(s) => s,
96 Self::Int(_) | Self::Float(_) => {
97 ""
100 }
101 }
102 }
103
104 #[must_use]
106 pub fn as_int(&self) -> Option<i64> {
107 match self {
108 Self::Int(n) => Some(*n),
109 _ => None,
110 }
111 }
112
113 #[must_use]
115 pub fn as_float(&self) -> Option<f64> {
116 match self {
117 Self::Float(n) => Some(*n),
118 _ => None,
119 }
120 }
121
122 #[must_use]
124 pub fn into_string(self) -> Option<String> {
125 match self {
126 Self::Str(s) | Self::Uuid(s) | Self::Path(s) => Some(s),
127 Self::Int(_) | Self::Float(_) => None,
128 }
129 }
130}
131
132#[derive(Debug, Clone, PartialEq, Eq)]
134pub enum ConversionError {
135 InvalidInt {
137 value: String,
139 param: String,
141 },
142 InvalidFloat {
144 value: String,
146 param: String,
148 },
149 InvalidUuid {
151 value: String,
153 param: String,
155 },
156}
157
158impl fmt::Display for ConversionError {
159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160 match self {
161 Self::InvalidInt { value, param } => {
162 write!(
163 f,
164 "path parameter '{param}': '{value}' is not a valid integer"
165 )
166 }
167 Self::InvalidFloat { value, param } => {
168 write!(
169 f,
170 "path parameter '{param}': '{value}' is not a valid float"
171 )
172 }
173 Self::InvalidUuid { value, param } => {
174 write!(f, "path parameter '{param}': '{value}' is not a valid UUID")
175 }
176 }
177 }
178}
179
180impl std::error::Error for ConversionError {}
181
182impl Converter {
183 #[must_use]
185 pub fn matches(&self, value: &str) -> bool {
186 match self {
187 Self::Str => true,
188 Self::Int => value.parse::<i64>().is_ok(),
189 Self::Float => value.parse::<f64>().is_ok(),
190 Self::Uuid => is_uuid(value),
191 Self::Path => true,
192 }
193 }
194
195 pub fn convert(&self, value: &str, param_name: &str) -> Result<ParamValue, ConversionError> {
201 match self {
202 Self::Str => Ok(ParamValue::Str(value.to_string())),
203 Self::Int => {
204 value
205 .parse::<i64>()
206 .map(ParamValue::Int)
207 .map_err(|_| ConversionError::InvalidInt {
208 value: value.to_string(),
209 param: param_name.to_string(),
210 })
211 }
212 Self::Float => value.parse::<f64>().map(ParamValue::Float).map_err(|_| {
213 ConversionError::InvalidFloat {
214 value: value.to_string(),
215 param: param_name.to_string(),
216 }
217 }),
218 Self::Uuid => {
219 if is_uuid(value) {
220 Ok(ParamValue::Uuid(value.to_string()))
221 } else {
222 Err(ConversionError::InvalidUuid {
223 value: value.to_string(),
224 param: param_name.to_string(),
225 })
226 }
227 }
228 Self::Path => Ok(ParamValue::Path(value.to_string())),
229 }
230 }
231
232 #[must_use]
234 pub fn type_name(&self) -> &'static str {
235 match self {
236 Self::Str => "string",
237 Self::Int => "integer",
238 Self::Float => "float",
239 Self::Uuid => "UUID",
240 Self::Path => "path",
241 }
242 }
243}
244
245fn is_uuid(s: &str) -> bool {
249 if s.len() != 36 {
251 return false;
252 }
253
254 let bytes = s.as_bytes();
255
256 if bytes[8] != b'-' || bytes[13] != b'-' || bytes[18] != b'-' || bytes[23] != b'-' {
258 return false;
259 }
260
261 bytes.iter().enumerate().all(|(i, &b)| {
263 if i == 8 || i == 13 || i == 18 || i == 23 {
264 true } else {
266 b.is_ascii_hexdigit()
267 }
268 })
269}
270
271#[derive(Debug, Clone, Default)]
273pub struct ParamInfo {
274 pub name: String,
276 pub converter: Converter,
278 pub title: Option<String>,
280 pub description: Option<String>,
282 pub deprecated: bool,
284 pub example: Option<serde_json::Value>,
286 pub examples: Vec<(String, serde_json::Value)>,
288}
289
290impl ParamInfo {
291 #[must_use]
293 pub fn new(name: impl Into<String>, converter: Converter) -> Self {
294 Self {
295 name: name.into(),
296 converter,
297 title: None,
298 description: None,
299 deprecated: false,
300 example: None,
301 examples: Vec::new(),
302 }
303 }
304
305 #[must_use]
307 pub fn with_title(mut self, title: impl Into<String>) -> Self {
308 self.title = Some(title.into());
309 self
310 }
311
312 #[must_use]
314 pub fn with_description(mut self, description: impl Into<String>) -> Self {
315 self.description = Some(description.into());
316 self
317 }
318
319 #[must_use]
321 pub fn deprecated(mut self) -> Self {
322 self.deprecated = true;
323 self
324 }
325
326 #[must_use]
328 pub fn with_example(mut self, example: serde_json::Value) -> Self {
329 self.example = Some(example);
330 self
331 }
332
333 #[must_use]
335 pub fn with_named_example(mut self, name: impl Into<String>, value: serde_json::Value) -> Self {
336 self.examples.push((name.into(), value));
337 self
338 }
339}
340
341#[must_use]
368pub fn extract_path_params(path: &str) -> Vec<ParamInfo> {
369 path.split('/')
370 .filter(|s| !s.is_empty())
371 .filter_map(|s| {
372 if s.starts_with('{') && s.ends_with('}') {
373 let inner = &s[1..s.len() - 1];
374 if let Some(name) = inner.strip_prefix('*') {
376 return Some(ParamInfo::new(name, Converter::Path));
377 }
378 let (name, converter) = if let Some(pos) = inner.find(':') {
379 let conv = match &inner[pos + 1..] {
380 "int" => Converter::Int,
381 "float" => Converter::Float,
382 "uuid" => Converter::Uuid,
383 "path" => Converter::Path,
384 _ => Converter::Str,
385 };
386 (&inner[..pos], conv)
387 } else {
388 (inner, Converter::Str)
389 };
390 Some(ParamInfo::new(name, converter))
391 } else {
392 None
393 }
394 })
395 .collect()
396}
397
398fn sanitize_operation_id(s: &str) -> String {
402 let mut out = String::with_capacity(s.len());
403 let mut prev_underscore = false;
404 for c in s.chars() {
405 if c.is_ascii_alphanumeric() {
406 out.push(c.to_ascii_lowercase());
407 prev_underscore = false;
408 } else if !prev_underscore {
409 out.push('_');
410 prev_underscore = true;
411 }
412 }
413 let trimmed = out.trim_matches('_');
414 if trimmed.is_empty() {
415 "root".to_string()
416 } else {
417 trimmed.to_string()
418 }
419}
420
421#[derive(Debug, Clone)]
426pub struct RouteResponse {
427 pub status: u16,
429 pub schema_name: String,
431 pub description: String,
433 pub content_type: String,
435}
436
437impl RouteResponse {
438 #[must_use]
440 pub fn new(
441 status: u16,
442 schema_name: impl Into<String>,
443 description: impl Into<String>,
444 ) -> Self {
445 Self {
446 status,
447 schema_name: schema_name.into(),
448 description: description.into(),
449 content_type: "application/json".to_string(),
450 }
451 }
452
453 #[must_use]
455 pub fn with_content_type(mut self, content_type: impl Into<String>) -> Self {
456 self.content_type = content_type.into();
457 self
458 }
459}
460
461#[derive(Debug, Clone, Default)]
465pub struct RouteSecurityRequirement {
466 pub scheme: String,
468 pub scopes: Vec<String>,
470}
471
472impl RouteSecurityRequirement {
473 #[must_use]
475 pub fn new(scheme: impl Into<String>) -> Self {
476 Self {
477 scheme: scheme.into(),
478 scopes: Vec::new(),
479 }
480 }
481
482 #[must_use]
484 pub fn with_scopes(
485 scheme: impl Into<String>,
486 scopes: impl IntoIterator<Item = impl Into<String>>,
487 ) -> Self {
488 Self {
489 scheme: scheme.into(),
490 scopes: scopes.into_iter().map(Into::into).collect(),
491 }
492 }
493}
494
495#[derive(Clone)]
510pub struct Route {
511 pub path: String,
513 pub method: Method,
515 pub operation_id: String,
517 pub summary: Option<String>,
519 pub description: Option<String>,
521 pub tags: Vec<String>,
523 pub deprecated: bool,
525 pub path_params: Vec<ParamInfo>,
527 pub request_body_schema: Option<String>,
529 pub request_body_content_type: Option<String>,
531 pub request_body_required: bool,
533 pub security: Vec<RouteSecurityRequirement>,
538 pub responses: Vec<RouteResponse>,
542}
543
544impl fmt::Debug for Route {
545 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
546 let mut s = f.debug_struct("Route");
547 s.field("path", &self.path)
548 .field("method", &self.method)
549 .field("operation_id", &self.operation_id);
550 if let Some(ref summary) = self.summary {
551 s.field("summary", summary);
552 }
553 if let Some(ref desc) = self.description {
554 s.field("description", desc);
555 }
556 if !self.tags.is_empty() {
557 s.field("tags", &self.tags);
558 }
559 if self.deprecated {
560 s.field("deprecated", &self.deprecated);
561 }
562 if !self.path_params.is_empty() {
563 s.field("path_params", &self.path_params);
564 }
565 if let Some(ref schema) = self.request_body_schema {
566 s.field("request_body_schema", schema);
567 }
568 if let Some(ref content_type) = self.request_body_content_type {
569 s.field("request_body_content_type", content_type);
570 }
571 if self.request_body_required {
572 s.field("request_body_required", &self.request_body_required);
573 }
574 if !self.security.is_empty() {
575 s.field("security", &self.security);
576 }
577 if !self.responses.is_empty() {
578 s.field("responses", &self.responses);
579 }
580 s.finish()
581 }
582}
583
584#[derive(Debug, Clone)]
586pub struct RouteConflictError {
587 pub method: Method,
589 pub new_path: String,
591 pub existing_path: String,
593}
594
595impl fmt::Display for RouteConflictError {
596 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
597 write!(
598 f,
599 "route conflict for {}: {} conflicts with {}",
600 self.method, self.new_path, self.existing_path
601 )
602 }
603}
604
605impl std::error::Error for RouteConflictError {}
606
607#[derive(Debug, Clone)]
609pub struct InvalidRouteError {
610 pub path: String,
612 pub message: String,
614}
615
616impl InvalidRouteError {
617 #[must_use]
619 pub fn new(path: impl Into<String>, message: impl Into<String>) -> Self {
620 Self {
621 path: path.into(),
622 message: message.into(),
623 }
624 }
625}
626
627impl fmt::Display for InvalidRouteError {
628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
629 write!(f, "invalid route path '{}': {}", self.path, self.message)
630 }
631}
632
633impl std::error::Error for InvalidRouteError {}
634
635#[derive(Debug, Clone)]
637pub enum RouteAddError {
638 Conflict(RouteConflictError),
640 InvalidPath(InvalidRouteError),
642}
643
644impl fmt::Display for RouteAddError {
645 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
646 match self {
647 Self::Conflict(err) => err.fmt(f),
648 Self::InvalidPath(err) => err.fmt(f),
649 }
650 }
651}
652
653impl std::error::Error for RouteAddError {
654 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
655 match self {
656 Self::Conflict(err) => Some(err),
657 Self::InvalidPath(err) => Some(err),
658 }
659 }
660}
661
662impl From<RouteConflictError> for RouteAddError {
663 fn from(err: RouteConflictError) -> Self {
664 Self::Conflict(err)
665 }
666}
667
668impl From<InvalidRouteError> for RouteAddError {
669 fn from(err: InvalidRouteError) -> Self {
670 Self::InvalidPath(err)
671 }
672}
673
674impl Route {
675 pub fn new(method: Method, path: impl Into<String>) -> Self {
691 let path = path.into();
692 let method_prefix = method.as_str().to_ascii_lowercase();
695 let path_part = sanitize_operation_id(&path);
696 let operation_id = format!("{method_prefix}_{path_part}");
697 let path_params = extract_path_params(&path);
698 Self {
699 path,
700 method,
701 operation_id,
702 summary: None,
703 description: None,
704 tags: Vec::new(),
705 deprecated: false,
706 path_params,
707 request_body_schema: None,
708 request_body_content_type: None,
709 request_body_required: false,
710 security: Vec::new(),
711 responses: Vec::new(),
712 }
713 }
714
715 #[must_use]
721 pub fn with_placeholder_handler(method: Method, path: impl Into<String>) -> Self {
722 Self::new(method, path)
723 }
724
725 #[must_use]
727 pub fn summary(mut self, summary: impl Into<String>) -> Self {
728 self.summary = Some(summary.into());
729 self
730 }
731
732 #[must_use]
734 pub fn description(mut self, description: impl Into<String>) -> Self {
735 self.description = Some(description.into());
736 self
737 }
738
739 #[must_use]
741 pub fn operation_id(mut self, operation_id: impl Into<String>) -> Self {
742 self.operation_id = operation_id.into();
743 self
744 }
745
746 #[must_use]
748 pub fn tag(mut self, tag: impl Into<String>) -> Self {
749 self.tags.push(tag.into());
750 self
751 }
752
753 #[must_use]
755 pub fn tags(mut self, tags: impl IntoIterator<Item = impl Into<String>>) -> Self {
756 self.tags.extend(tags.into_iter().map(Into::into));
757 self
758 }
759
760 #[must_use]
762 pub fn deprecated(mut self) -> Self {
763 self.deprecated = true;
764 self
765 }
766
767 #[must_use]
772 pub fn request_body(
773 mut self,
774 schema: impl Into<String>,
775 content_type: impl Into<String>,
776 required: bool,
777 ) -> Self {
778 self.request_body_schema = Some(schema.into());
779 self.request_body_content_type = Some(content_type.into());
780 self.request_body_required = required;
781 self
782 }
783
784 #[must_use]
805 pub fn security(
806 mut self,
807 scheme: impl Into<String>,
808 scopes: impl IntoIterator<Item = impl Into<String>>,
809 ) -> Self {
810 self.security
811 .push(RouteSecurityRequirement::with_scopes(scheme, scopes));
812 self
813 }
814
815 #[must_use]
829 pub fn security_scheme(mut self, scheme: impl Into<String>) -> Self {
830 self.security.push(RouteSecurityRequirement::new(scheme));
831 self
832 }
833
834 #[must_use]
856 pub fn response(
857 mut self,
858 status: u16,
859 schema_name: impl Into<String>,
860 description: impl Into<String>,
861 ) -> Self {
862 self.responses
863 .push(RouteResponse::new(status, schema_name, description));
864 self
865 }
866
867 #[must_use]
869 pub fn has_responses(&self) -> bool {
870 !self.responses.is_empty()
871 }
872
873 #[must_use]
875 pub fn has_request_body(&self) -> bool {
876 self.request_body_schema.is_some()
877 }
878
879 #[must_use]
881 pub fn has_path_params(&self) -> bool {
882 !self.path_params.is_empty()
883 }
884
885 #[must_use]
887 pub fn has_security(&self) -> bool {
888 !self.security.is_empty()
889 }
890}
891
892struct Node {
894 segment: String,
895 children: Vec<Node>,
896 param: Option<ParamInfo>,
897 routes: HashMap<Method, usize>,
898}
899
900impl Node {
901 fn new(segment: impl Into<String>) -> Self {
902 Self {
903 segment: segment.into(),
904 children: Vec::new(),
905 param: None,
906 routes: HashMap::new(),
907 }
908 }
909
910 fn find_static(&self, segment: &str) -> Option<&Node> {
911 self.children
912 .iter()
913 .find(|c| c.param.is_none() && c.segment == segment)
914 }
915}
916
917pub struct Router {
919 root: Node,
920 routes: Vec<Route>,
921}
922
923impl Router {
924 #[must_use]
926 pub fn new() -> Self {
927 Self {
928 root: Node::new(""),
929 routes: Vec::new(),
930 }
931 }
932
933 pub fn add(&mut self, route: Route) -> Result<(), RouteAddError> {
942 if let Some(conflict) = self.find_conflict(&route) {
943 return Err(RouteAddError::Conflict(conflict));
944 }
945
946 let route_idx = self.routes.len();
947 let path = route.path.clone();
948 let method = route.method;
949 self.routes.push(route);
950
951 let segments = parse_path(&path);
952 validate_path_segments(&path, &segments)?;
953 let mut node = &mut self.root;
954
955 for seg in segments {
956 let (segment, param) = match seg {
957 PathSegment::Static(s) => (s.to_string(), None),
958 PathSegment::Param { name, converter } => {
959 let info = ParamInfo::new(name, converter);
960 (format!("{{{name}}}"), Some(info))
961 }
962 };
963
964 let child_idx = node.children.iter().position(|c| c.segment == segment);
966
967 if let Some(idx) = child_idx {
968 node = &mut node.children[idx];
969 } else {
970 let mut new_node = Node::new(&segment);
971 new_node.param = param;
972 node.children.push(new_node);
973 node = node.children.last_mut().unwrap();
974 }
975 }
976
977 node.routes.insert(method, route_idx);
978 Ok(())
979 }
980
981 #[must_use]
983 pub fn lookup<'a>(&'a self, path: &'a str, method: Method) -> RouteLookup<'a> {
984 let (node, params) = match self.match_node(path) {
985 Some(found) => found,
986 None => return RouteLookup::NotFound,
987 };
988
989 if let Some(&idx) = node.routes.get(&method) {
990 return RouteLookup::Match(RouteMatch {
991 route: &self.routes[idx],
992 params,
993 });
994 }
995
996 if method == Method::Head
998 && let Some(&idx) = node.routes.get(&Method::Get)
999 {
1000 return RouteLookup::Match(RouteMatch {
1001 route: &self.routes[idx],
1002 params,
1003 });
1004 }
1005
1006 if node.routes.is_empty() {
1007 return RouteLookup::NotFound;
1008 }
1009
1010 let allowed = AllowedMethods::new(node.routes.keys().copied().collect());
1011 RouteLookup::MethodNotAllowed { allowed }
1012 }
1013
1014 #[must_use]
1016 pub fn match_path<'a>(&'a self, path: &'a str, method: Method) -> Option<RouteMatch<'a>> {
1017 match self.lookup(path, method) {
1018 RouteLookup::Match(matched) => Some(matched),
1019 RouteLookup::MethodNotAllowed { .. } | RouteLookup::NotFound => None,
1020 }
1021 }
1022
1023 #[must_use]
1025 pub fn routes(&self) -> &[Route] {
1026 &self.routes
1027 }
1028
1029 pub fn mount(mut self, prefix: &str, child: Router) -> Result<Self, RouteAddError> {
1057 let prefix = prefix.trim_end_matches('/');
1058
1059 for route in child.routes {
1060 let child_path = if route.path == "/" {
1061 String::new()
1062 } else if route.path.starts_with('/') {
1063 route.path.clone()
1064 } else {
1065 format!("/{}", route.path)
1066 };
1067
1068 let full_path = if prefix.is_empty() {
1069 if child_path.is_empty() {
1070 "/".to_string()
1071 } else {
1072 child_path
1073 }
1074 } else if child_path.is_empty() {
1075 prefix.to_string()
1076 } else {
1077 format!("{}{}", prefix, child_path)
1078 };
1079
1080 let path_params = extract_path_params(&full_path);
1082 let mounted = Route {
1083 path: full_path,
1084 method: route.method,
1085 operation_id: route.operation_id,
1086 summary: route.summary,
1087 description: route.description,
1088 tags: route.tags,
1089 deprecated: route.deprecated,
1090 path_params,
1091 request_body_schema: route.request_body_schema,
1092 request_body_content_type: route.request_body_content_type,
1093 request_body_required: route.request_body_required,
1094 security: route.security,
1095 responses: route.responses,
1096 };
1097
1098 self.add(mounted)?;
1099 }
1100
1101 Ok(self)
1102 }
1103
1104 #[must_use]
1112 pub fn nest(self, prefix: &str, child: Router) -> Self {
1113 self.mount(prefix, child)
1114 .expect("route conflict when nesting router")
1115 }
1116
1117 fn find_conflict(&self, route: &Route) -> Option<RouteConflictError> {
1118 for existing in &self.routes {
1119 if existing.method != route.method {
1120 continue;
1121 }
1122
1123 if paths_conflict(&existing.path, &route.path) {
1124 return Some(RouteConflictError {
1125 method: route.method,
1126 new_path: route.path.clone(),
1127 existing_path: existing.path.clone(),
1128 });
1129 }
1130 }
1131
1132 None
1133 }
1134
1135 fn match_node<'a>(&'a self, path: &'a str) -> Option<(&'a Node, Vec<(&'a str, &'a str)>)> {
1136 let mut range_iter = SegmentRangeIter::new(path);
1138
1139 let mut ranges_buf: [(usize, usize); 16] = [(0, 0); 16];
1142 let mut ranges_vec: Vec<(usize, usize)> = Vec::new();
1143 let mut range_count = 0;
1144
1145 for range in &mut range_iter {
1146 match range_count.cmp(&16) {
1147 std::cmp::Ordering::Less => {
1148 ranges_buf[range_count] = range;
1149 }
1150 std::cmp::Ordering::Equal => {
1151 ranges_vec = ranges_buf.to_vec();
1153 ranges_vec.push(range);
1154 }
1155 std::cmp::Ordering::Greater => {
1156 ranges_vec.push(range);
1157 }
1158 }
1159 range_count += 1;
1160 }
1161
1162 let ranges: &[(usize, usize)] = if range_count <= 16 {
1163 &ranges_buf[..range_count]
1164 } else {
1165 &ranges_vec
1166 };
1167
1168 let last_end = ranges.last().map_or(0, |(_, end)| *end);
1169 let mut params = Vec::new();
1170 let node = Self::walk(&self.root, path, ranges, 0, last_end, &mut params)?;
1171 Some((node, params))
1172 }
1173
1174 fn walk<'a>(
1190 node: &'a Node,
1191 path: &'a str,
1192 ranges: &[(usize, usize)],
1193 idx: usize,
1194 last_end: usize,
1195 params: &mut Vec<(&'a str, &'a str)>,
1196 ) -> Option<&'a Node> {
1197 if idx == ranges.len() {
1198 return if node.routes.is_empty() {
1199 None
1200 } else {
1201 Some(node)
1202 };
1203 }
1204 let (start, end) = ranges[idx];
1205 let segment = &path[start..end];
1206
1207 if let Some(child) = node.find_static(segment)
1209 && let Some(found) = Self::walk(child, path, ranges, idx + 1, last_end, params)
1210 {
1211 return Some(found);
1212 }
1213
1214 for child in node.children.iter().filter(|c| c.param.is_some()) {
1216 let Some(ref info) = child.param else {
1217 continue;
1218 };
1219 if info.converter == Converter::Path {
1220 if child.routes.is_empty() {
1222 continue;
1223 }
1224 params.push((info.name.as_str(), &path[start..last_end]));
1225 return Some(child);
1226 }
1227 if !info.converter.matches(segment) {
1228 continue;
1229 }
1230 params.push((info.name.as_str(), segment));
1231 if let Some(found) = Self::walk(child, path, ranges, idx + 1, last_end, params) {
1232 return Some(found);
1233 }
1234 params.pop();
1235 }
1236
1237 None
1238 }
1239}
1240
1241impl Default for Router {
1242 fn default() -> Self {
1243 Self::new()
1244 }
1245}
1246
1247enum PathSegment<'a> {
1248 Static(&'a str),
1249 Param { name: &'a str, converter: Converter },
1250}
1251
1252fn parse_path(path: &str) -> Vec<PathSegment<'_>> {
1253 path.split('/')
1254 .filter(|s| !s.is_empty())
1255 .map(|s| {
1256 if s.starts_with('{') && s.ends_with('}') {
1257 let inner = &s[1..s.len() - 1];
1258 if let Some(name) = inner.strip_prefix('*') {
1260 return PathSegment::Param {
1261 name,
1262 converter: Converter::Path,
1263 };
1264 }
1265 let (name, converter) = if let Some(pos) = inner.find(':') {
1266 let conv = match &inner[pos + 1..] {
1267 "int" => Converter::Int,
1268 "float" => Converter::Float,
1269 "uuid" => Converter::Uuid,
1270 "path" => Converter::Path,
1271 _ => Converter::Str,
1272 };
1273 (&inner[..pos], conv)
1274 } else {
1275 (inner, Converter::Str)
1276 };
1277 PathSegment::Param { name, converter }
1278 } else {
1279 PathSegment::Static(s)
1280 }
1281 })
1282 .collect()
1283}
1284
1285fn validate_path_segments(
1286 path: &str,
1287 segments: &[PathSegment<'_>],
1288) -> Result<(), InvalidRouteError> {
1289 for (idx, segment) in segments.iter().enumerate() {
1290 if let PathSegment::Param {
1291 name,
1292 converter: Converter::Path,
1293 } = segment
1294 && idx + 1 != segments.len()
1295 {
1296 return Err(InvalidRouteError::new(
1297 path,
1298 format!("wildcard '{{*{name}}}' or '{{{name}:path}}' must be the final segment"),
1299 ));
1300 }
1301 }
1302 Ok(())
1303}
1304
1305struct SegmentRangeIter<'a> {
1309 bytes: &'a [u8],
1310 idx: usize,
1311}
1312
1313impl<'a> SegmentRangeIter<'a> {
1314 fn new(path: &'a str) -> Self {
1315 Self {
1316 bytes: path.as_bytes(),
1317 idx: 0,
1318 }
1319 }
1320}
1321
1322impl Iterator for SegmentRangeIter<'_> {
1323 type Item = (usize, usize);
1324
1325 #[inline]
1326 fn next(&mut self) -> Option<Self::Item> {
1327 while self.idx < self.bytes.len() && self.bytes[self.idx] == b'/' {
1329 self.idx += 1;
1330 }
1331 if self.idx >= self.bytes.len() {
1332 return None;
1333 }
1334 let start = self.idx;
1335 while self.idx < self.bytes.len() && self.bytes[self.idx] != b'/' {
1337 self.idx += 1;
1338 }
1339 Some((start, self.idx))
1340 }
1341
1342 fn size_hint(&self) -> (usize, Option<usize>) {
1343 let remaining = self.bytes.len().saturating_sub(self.idx);
1345 (0, Some(remaining / 2 + 1))
1346 }
1347}
1348
1349fn paths_conflict(a: &str, b: &str) -> bool {
1350 let a_segments = parse_path(a);
1351 let b_segments = parse_path(b);
1352
1353 let a_has_path = matches!(
1354 a_segments.last(),
1355 Some(PathSegment::Param {
1356 converter: Converter::Path,
1357 ..
1358 })
1359 );
1360 let b_has_path = matches!(
1361 b_segments.last(),
1362 Some(PathSegment::Param {
1363 converter: Converter::Path,
1364 ..
1365 })
1366 );
1367 let min_len = a_segments.len().min(b_segments.len());
1368 let mut param_mismatch = false;
1369
1370 for (left, right) in a_segments.iter().take(min_len).zip(b_segments.iter()) {
1371 match (left, right) {
1372 (PathSegment::Static(a), PathSegment::Static(b)) => {
1373 if a != b {
1374 return false;
1375 }
1376 }
1377 (PathSegment::Static(_), PathSegment::Param { .. })
1378 | (PathSegment::Param { .. }, PathSegment::Static(_)) => {
1379 return false;
1381 }
1382 (
1383 PathSegment::Param {
1384 name: left_name,
1385 converter: left_conv,
1386 },
1387 PathSegment::Param {
1388 name: right_name,
1389 converter: right_conv,
1390 },
1391 ) => {
1392 if left_name != right_name || left_conv != right_conv {
1393 param_mismatch = true;
1394 }
1395 }
1396 }
1397 }
1398
1399 if a_segments.len() == b_segments.len() {
1400 return true;
1401 }
1402
1403 if param_mismatch {
1404 return true;
1405 }
1406
1407 if a_has_path && a_segments.len() == min_len {
1408 return true;
1409 }
1410
1411 if b_has_path && b_segments.len() == min_len {
1412 return true;
1413 }
1414
1415 false
1416}
1417
1418#[cfg(test)]
1419mod tests {
1420 use super::*;
1421
1422 fn route(method: Method, path: &str) -> Route {
1424 Route::new(method, path)
1425 }
1426
1427 #[test]
1428 fn static_route_match() {
1429 let mut router = Router::new();
1430 router.add(route(Method::Get, "/users")).unwrap();
1431 router.add(route(Method::Get, "/items")).unwrap();
1432
1433 let m = router.match_path("/users", Method::Get);
1434 assert!(m.is_some());
1435 assert_eq!(m.unwrap().route.path, "/users");
1436
1437 let m = router.match_path("/items", Method::Get);
1438 assert!(m.is_some());
1439 assert_eq!(m.unwrap().route.path, "/items");
1440
1441 assert!(router.match_path("/other", Method::Get).is_none());
1443 }
1444
1445 #[test]
1446 fn nested_static_routes() {
1447 let mut router = Router::new();
1448 router.add(route(Method::Get, "/api/v1/users")).unwrap();
1449 router.add(route(Method::Get, "/api/v2/users")).unwrap();
1450
1451 let m = router.match_path("/api/v1/users", Method::Get);
1452 assert!(m.is_some());
1453 assert_eq!(m.unwrap().route.path, "/api/v1/users");
1454
1455 let m = router.match_path("/api/v2/users", Method::Get);
1456 assert!(m.is_some());
1457 assert_eq!(m.unwrap().route.path, "/api/v2/users");
1458 }
1459
1460 #[test]
1461 fn parameter_extraction() {
1462 let mut router = Router::new();
1463 router.add(route(Method::Get, "/users/{user_id}")).unwrap();
1464
1465 let m = router.match_path("/users/123", Method::Get);
1466 assert!(m.is_some());
1467 let m = m.unwrap();
1468 assert_eq!(m.route.path, "/users/{user_id}");
1469 assert_eq!(m.params.len(), 1);
1470 assert_eq!(m.params[0], ("user_id", "123"));
1471 }
1472
1473 #[test]
1474 fn multiple_parameters() {
1475 let mut router = Router::new();
1476 router
1477 .add(route(Method::Get, "/users/{user_id}/posts/{post_id}"))
1478 .unwrap();
1479
1480 let m = router.match_path("/users/42/posts/99", Method::Get);
1481 assert!(m.is_some());
1482 let m = m.unwrap();
1483 assert_eq!(m.params.len(), 2);
1484 assert_eq!(m.params[0], ("user_id", "42"));
1485 assert_eq!(m.params[1], ("post_id", "99"));
1486 }
1487
1488 #[test]
1489 fn int_converter() {
1490 let mut router = Router::new();
1491 router.add(route(Method::Get, "/items/{id:int}")).unwrap();
1492
1493 let m = router.match_path("/items/123", Method::Get);
1495 assert!(m.is_some());
1496 assert_eq!(m.unwrap().params[0], ("id", "123"));
1497
1498 let m = router.match_path("/items/-456", Method::Get);
1500 assert!(m.is_some());
1501
1502 assert!(router.match_path("/items/abc", Method::Get).is_none());
1504 assert!(router.match_path("/items/12.34", Method::Get).is_none());
1505 }
1506
1507 #[test]
1508 fn float_converter() {
1509 let mut router = Router::new();
1510 router
1511 .add(route(Method::Get, "/values/{val:float}"))
1512 .unwrap();
1513
1514 let m = router.match_path("/values/3.14", Method::Get);
1516 assert!(m.is_some());
1517 assert_eq!(m.unwrap().params[0], ("val", "3.14"));
1518
1519 let m = router.match_path("/values/42", Method::Get);
1521 assert!(m.is_some());
1522
1523 assert!(router.match_path("/values/abc", Method::Get).is_none());
1525 }
1526
1527 #[test]
1528 fn uuid_converter() {
1529 let mut router = Router::new();
1530 router
1531 .add(route(Method::Get, "/objects/{id:uuid}"))
1532 .unwrap();
1533
1534 let m = router.match_path("/objects/550e8400-e29b-41d4-a716-446655440000", Method::Get);
1536 assert!(m.is_some());
1537 assert_eq!(
1538 m.unwrap().params[0],
1539 ("id", "550e8400-e29b-41d4-a716-446655440000")
1540 );
1541
1542 assert!(
1544 router
1545 .match_path("/objects/not-a-uuid", Method::Get)
1546 .is_none()
1547 );
1548 assert!(router.match_path("/objects/123", Method::Get).is_none());
1549 }
1550
1551 #[test]
1552 fn path_converter_captures_slashes() {
1553 let mut router = Router::new();
1554 router
1555 .add(route(Method::Get, "/files/{path:path}"))
1556 .unwrap();
1557
1558 let m = router.match_path("/files/a/b/c.txt", Method::Get).unwrap();
1559 assert_eq!(m.params[0], ("path", "a/b/c.txt"));
1560 }
1561
1562 #[test]
1563 fn path_converter_must_be_terminal() {
1564 let mut router = Router::new();
1565 let result = router.add(route(Method::Get, "/files/{path:path}/edit"));
1566 assert!(matches!(result, Err(RouteAddError::InvalidPath(_))));
1567 }
1568
1569 #[test]
1570 fn method_dispatch() {
1571 let mut router = Router::new();
1572 router.add(route(Method::Get, "/items")).unwrap();
1573 router.add(route(Method::Post, "/items")).unwrap();
1574 router.add(route(Method::Delete, "/items/{id}")).unwrap();
1575
1576 let m = router.match_path("/items", Method::Get);
1578 assert!(m.is_some());
1579 assert_eq!(m.unwrap().route.method, Method::Get);
1580
1581 let m = router.match_path("/items", Method::Post);
1583 assert!(m.is_some());
1584 assert_eq!(m.unwrap().route.method, Method::Post);
1585
1586 let m = router.match_path("/items/123", Method::Delete);
1588 assert!(m.is_some());
1589 assert_eq!(m.unwrap().route.method, Method::Delete);
1590
1591 assert!(router.match_path("/items", Method::Put).is_none());
1593 }
1594
1595 #[test]
1596 fn lookup_method_not_allowed_includes_head() {
1597 let mut router = Router::new();
1598 router.add(route(Method::Get, "/users")).unwrap();
1599
1600 let result = router.lookup("/users", Method::Post);
1601 match result {
1602 RouteLookup::MethodNotAllowed { allowed } => {
1603 assert!(allowed.contains(Method::Get));
1604 assert!(allowed.contains(Method::Head));
1605 assert_eq!(allowed.header_value(), "GET, HEAD");
1606 }
1607 _ => panic!("expected MethodNotAllowed"),
1608 }
1609 }
1610
1611 #[test]
1612 fn lookup_method_not_allowed_multiple_methods() {
1613 let mut router = Router::new();
1614 router.add(route(Method::Get, "/users")).unwrap();
1615 router.add(route(Method::Post, "/users")).unwrap();
1616 router.add(route(Method::Delete, "/users")).unwrap();
1617
1618 let result = router.lookup("/users", Method::Put);
1619 match result {
1620 RouteLookup::MethodNotAllowed { allowed } => {
1621 assert_eq!(allowed.header_value(), "GET, HEAD, POST, DELETE");
1622 }
1623 _ => panic!("expected MethodNotAllowed"),
1624 }
1625 }
1626
1627 #[test]
1628 fn lookup_not_found_when_path_missing() {
1629 let mut router = Router::new();
1630 router.add(route(Method::Get, "/users")).unwrap();
1631
1632 assert!(matches!(
1633 router.lookup("/missing", Method::Get),
1634 RouteLookup::NotFound
1635 ));
1636 }
1637
1638 #[test]
1639 fn lookup_not_found_when_converter_mismatch() {
1640 let mut router = Router::new();
1641 router.add(route(Method::Get, "/items/{id:int}")).unwrap();
1642
1643 assert!(matches!(
1644 router.lookup("/items/abc", Method::Get),
1645 RouteLookup::NotFound
1646 ));
1647 }
1648
1649 #[test]
1650 fn static_takes_priority_over_param() {
1651 let mut router = Router::new();
1652 router.add(route(Method::Get, "/users/me")).unwrap();
1654 router.add(route(Method::Get, "/users/{id}")).unwrap();
1655
1656 let m = router.match_path("/users/me", Method::Get);
1658 assert!(m.is_some());
1659 let m = m.unwrap();
1660 assert_eq!(m.route.path, "/users/me");
1661 assert!(m.params.is_empty());
1662
1663 let m = router.match_path("/users/123", Method::Get);
1665 assert!(m.is_some());
1666 let m = m.unwrap();
1667 assert_eq!(m.route.path, "/users/{id}");
1668 assert_eq!(m.params[0], ("id", "123"));
1669 }
1670
1671 #[test]
1672 fn route_match_get_param() {
1673 let mut router = Router::new();
1674 router
1675 .add(route(Method::Get, "/users/{user_id}/posts/{post_id}"))
1676 .unwrap();
1677
1678 let m = router
1679 .match_path("/users/42/posts/99", Method::Get)
1680 .unwrap();
1681
1682 assert_eq!(m.get_param("user_id"), Some("42"));
1683 assert_eq!(m.get_param("post_id"), Some("99"));
1684 assert_eq!(m.get_param("unknown"), None);
1685 }
1686
1687 #[test]
1688 fn converter_matches() {
1689 assert!(Converter::Str.matches("anything"));
1690 assert!(Converter::Str.matches("123"));
1691
1692 assert!(Converter::Int.matches("123"));
1693 assert!(Converter::Int.matches("-456"));
1694 assert!(!Converter::Int.matches("12.34"));
1695 assert!(!Converter::Int.matches("abc"));
1696
1697 assert!(Converter::Float.matches("3.14"));
1698 assert!(Converter::Float.matches("42"));
1699 assert!(!Converter::Float.matches("abc"));
1700
1701 assert!(Converter::Uuid.matches("550e8400-e29b-41d4-a716-446655440000"));
1702 assert!(!Converter::Uuid.matches("not-a-uuid"));
1703
1704 assert!(Converter::Path.matches("any/path/here"));
1705 }
1706
1707 #[test]
1708 fn parse_path_segments() {
1709 let segments = parse_path("/users/{id}/posts/{post_id:int}");
1710 assert_eq!(segments.len(), 4);
1711
1712 match &segments[0] {
1713 PathSegment::Static(s) => assert_eq!(*s, "users"),
1714 _ => panic!("Expected static segment"),
1715 }
1716
1717 match &segments[1] {
1718 PathSegment::Param { name, converter } => {
1719 assert_eq!(*name, "id");
1720 assert_eq!(*converter, Converter::Str);
1721 }
1722 _ => panic!("Expected param segment"),
1723 }
1724
1725 match &segments[2] {
1726 PathSegment::Static(s) => assert_eq!(*s, "posts"),
1727 _ => panic!("Expected static segment"),
1728 }
1729
1730 match &segments[3] {
1731 PathSegment::Param { name, converter } => {
1732 assert_eq!(*name, "post_id");
1733 assert_eq!(*converter, Converter::Int);
1734 }
1735 _ => panic!("Expected param segment"),
1736 }
1737 }
1738
1739 #[test]
1744 fn extract_path_params_simple() {
1745 let params = extract_path_params("/users/{id}");
1746 assert_eq!(params.len(), 1);
1747 assert_eq!(params[0].name, "id");
1748 assert_eq!(params[0].converter, Converter::Str);
1749 }
1750
1751 #[test]
1752 fn extract_path_params_multiple() {
1753 let params = extract_path_params("/users/{id}/posts/{post_id}");
1754 assert_eq!(params.len(), 2);
1755 assert_eq!(params[0].name, "id");
1756 assert_eq!(params[1].name, "post_id");
1757 }
1758
1759 #[test]
1760 fn extract_path_params_typed_int() {
1761 let params = extract_path_params("/items/{item_id:int}");
1762 assert_eq!(params.len(), 1);
1763 assert_eq!(params[0].name, "item_id");
1764 assert_eq!(params[0].converter, Converter::Int);
1765 }
1766
1767 #[test]
1768 fn extract_path_params_typed_float() {
1769 let params = extract_path_params("/prices/{value:float}");
1770 assert_eq!(params.len(), 1);
1771 assert_eq!(params[0].name, "value");
1772 assert_eq!(params[0].converter, Converter::Float);
1773 }
1774
1775 #[test]
1776 fn extract_path_params_typed_uuid() {
1777 let params = extract_path_params("/resources/{uuid:uuid}");
1778 assert_eq!(params.len(), 1);
1779 assert_eq!(params[0].name, "uuid");
1780 assert_eq!(params[0].converter, Converter::Uuid);
1781 }
1782
1783 #[test]
1784 fn extract_path_params_wildcard_asterisk() {
1785 let params = extract_path_params("/files/{*filepath}");
1786 assert_eq!(params.len(), 1);
1787 assert_eq!(params[0].name, "filepath");
1788 assert_eq!(params[0].converter, Converter::Path);
1789 }
1790
1791 #[test]
1792 fn extract_path_params_wildcard_path_converter() {
1793 let params = extract_path_params("/static/{path:path}");
1794 assert_eq!(params.len(), 1);
1795 assert_eq!(params[0].name, "path");
1796 assert_eq!(params[0].converter, Converter::Path);
1797 }
1798
1799 #[test]
1800 fn extract_path_params_mixed_types() {
1801 let params = extract_path_params("/api/{version}/items/{id:int}/details/{slug}");
1802 assert_eq!(params.len(), 3);
1803 assert_eq!(params[0].name, "version");
1804 assert_eq!(params[0].converter, Converter::Str);
1805 assert_eq!(params[1].name, "id");
1806 assert_eq!(params[1].converter, Converter::Int);
1807 assert_eq!(params[2].name, "slug");
1808 assert_eq!(params[2].converter, Converter::Str);
1809 }
1810
1811 #[test]
1812 fn extract_path_params_no_params() {
1813 let params = extract_path_params("/static/path/no/params");
1814 assert!(params.is_empty());
1815 }
1816
1817 #[test]
1818 fn extract_path_params_root() {
1819 let params = extract_path_params("/");
1820 assert!(params.is_empty());
1821 }
1822
1823 #[test]
1828 fn param_info_new() {
1829 let info = ParamInfo::new("id", Converter::Int);
1830 assert_eq!(info.name, "id");
1831 assert_eq!(info.converter, Converter::Int);
1832 assert!(info.title.is_none());
1833 assert!(info.description.is_none());
1834 assert!(!info.deprecated);
1835 assert!(info.example.is_none());
1836 assert!(info.examples.is_empty());
1837 }
1838
1839 #[test]
1840 fn param_info_with_title() {
1841 let info = ParamInfo::new("id", Converter::Str).with_title("User ID");
1842 assert_eq!(info.title.as_deref(), Some("User ID"));
1843 }
1844
1845 #[test]
1846 fn param_info_with_description() {
1847 let info =
1848 ParamInfo::new("page", Converter::Int).with_description("Page number for pagination");
1849 assert_eq!(
1850 info.description.as_deref(),
1851 Some("Page number for pagination")
1852 );
1853 }
1854
1855 #[test]
1856 fn param_info_deprecated() {
1857 let info = ParamInfo::new("old", Converter::Str).deprecated();
1858 assert!(info.deprecated);
1859 }
1860
1861 #[test]
1862 fn param_info_with_example() {
1863 let info = ParamInfo::new("id", Converter::Int).with_example(serde_json::json!(42));
1864 assert_eq!(info.example, Some(serde_json::json!(42)));
1865 }
1866
1867 #[test]
1868 fn param_info_with_named_examples() {
1869 let info = ParamInfo::new("status", Converter::Str)
1870 .with_named_example("active", serde_json::json!("active"))
1871 .with_named_example("inactive", serde_json::json!("inactive"));
1872 assert_eq!(info.examples.len(), 2);
1873 assert_eq!(info.examples[0].0, "active");
1874 assert_eq!(info.examples[1].0, "inactive");
1875 }
1876
1877 #[test]
1878 fn param_info_builder_chain() {
1879 let info = ParamInfo::new("item_id", Converter::Int)
1880 .with_title("Item ID")
1881 .with_description("The unique item identifier")
1882 .deprecated()
1883 .with_example(serde_json::json!(123));
1884
1885 assert_eq!(info.name, "item_id");
1886 assert_eq!(info.converter, Converter::Int);
1887 assert_eq!(info.title.as_deref(), Some("Item ID"));
1888 assert_eq!(
1889 info.description.as_deref(),
1890 Some("The unique item identifier")
1891 );
1892 assert!(info.deprecated);
1893 assert_eq!(info.example, Some(serde_json::json!(123)));
1894 }
1895
1896 #[test]
1897 fn empty_router() {
1898 let router = Router::new();
1899 assert!(router.match_path("/anything", Method::Get).is_none());
1900 assert!(router.routes().is_empty());
1901 }
1902
1903 #[test]
1904 fn routes_accessor() {
1905 let mut router = Router::new();
1906 let _ = router.add(route(Method::Get, "/a"));
1907 let _ = router.add(route(Method::Post, "/b"));
1908
1909 assert_eq!(router.routes().len(), 2);
1910 assert_eq!(router.routes()[0].path, "/a");
1911 assert_eq!(router.routes()[1].path, "/b");
1912 }
1913
1914 #[test]
1919 fn conflict_same_method_same_path() {
1920 let mut router = Router::new();
1921 router.add(route(Method::Get, "/users")).unwrap();
1922
1923 let result = router.add(route(Method::Get, "/users"));
1924 assert!(result.is_err());
1925 let err = match result.unwrap_err() {
1926 RouteAddError::Conflict(err) => err,
1927 RouteAddError::InvalidPath(err) => {
1928 panic!("unexpected invalid path error: {err}")
1929 }
1930 };
1931 assert_eq!(err.method, Method::Get);
1932 assert_eq!(err.new_path, "/users");
1933 assert_eq!(err.existing_path, "/users");
1934 }
1935
1936 #[test]
1937 fn conflict_same_method_same_param_pattern() {
1938 let mut router = Router::new();
1939 router.add(route(Method::Get, "/users/{id}")).unwrap();
1940
1941 let result = router.add(route(Method::Get, "/users/{user_id}"));
1943 assert!(result.is_err());
1944 let err = match result.unwrap_err() {
1945 RouteAddError::Conflict(err) => err,
1946 RouteAddError::InvalidPath(err) => {
1947 panic!("unexpected invalid path error: {err}")
1948 }
1949 };
1950 assert_eq!(err.existing_path, "/users/{id}");
1951 assert_eq!(err.new_path, "/users/{user_id}");
1952 }
1953
1954 #[test]
1955 fn conflict_param_name_mismatch_across_lengths() {
1956 let mut router = Router::new();
1957 router.add(route(Method::Get, "/users/{id}/posts")).unwrap();
1958
1959 let result = router.add(route(Method::Get, "/users/{user_id}"));
1960 assert!(matches!(result, Err(RouteAddError::Conflict(_))));
1961 }
1962
1963 #[test]
1964 fn conflict_different_converter_same_position() {
1965 let mut router = Router::new();
1966 router.add(route(Method::Get, "/items/{id:int}")).unwrap();
1967
1968 let result = router.add(route(Method::Get, "/items/{id:uuid}"));
1970 assert!(matches!(result, Err(RouteAddError::Conflict(_))));
1971 }
1972
1973 #[test]
1974 fn no_conflict_different_methods() {
1975 let mut router = Router::new();
1976 router.add(route(Method::Get, "/users")).unwrap();
1977 router.add(route(Method::Post, "/users")).unwrap();
1978 router.add(route(Method::Put, "/users")).unwrap();
1979 router.add(route(Method::Delete, "/users")).unwrap();
1980 router.add(route(Method::Patch, "/users")).unwrap();
1981
1982 assert_eq!(router.routes().len(), 5);
1983 }
1984
1985 #[test]
1986 fn no_conflict_static_vs_param() {
1987 let mut router = Router::new();
1988 router.add(route(Method::Get, "/users/me")).unwrap();
1989 router.add(route(Method::Get, "/users/{id}")).unwrap();
1990
1991 assert_eq!(router.routes().len(), 2);
1993 }
1994
1995 #[test]
1996 fn no_conflict_different_path_lengths() {
1997 let mut router = Router::new();
1998 router.add(route(Method::Get, "/users")).unwrap();
1999 router.add(route(Method::Get, "/users/{id}")).unwrap();
2000 router.add(route(Method::Get, "/users/{id}/posts")).unwrap();
2001
2002 assert_eq!(router.routes().len(), 3);
2003 }
2004
2005 #[test]
2006 fn conflict_error_display() {
2007 let err = RouteConflictError {
2008 method: Method::Get,
2009 new_path: "/new".to_string(),
2010 existing_path: "/existing".to_string(),
2011 };
2012 let msg = format!("{}", err);
2013 assert!(msg.contains("GET"));
2014 assert!(msg.contains("/new"));
2015 assert!(msg.contains("/existing"));
2016 }
2017
2018 #[test]
2023 fn root_path() {
2024 let mut router = Router::new();
2025 router.add(route(Method::Get, "/")).unwrap();
2026
2027 let m = router.match_path("/", Method::Get);
2028 assert!(m.is_some());
2029 assert_eq!(m.unwrap().route.path, "/");
2030 }
2031
2032 #[test]
2033 fn trailing_slash_handling() {
2034 let mut router = Router::new();
2035 router.add(route(Method::Get, "/users")).unwrap();
2036
2037 let m = router.match_path("/users/", Method::Get);
2040 assert!(m.is_none() || m.is_some());
2042 }
2043
2044 #[test]
2045 fn multiple_consecutive_slashes() {
2046 let mut router = Router::new();
2047 router.add(route(Method::Get, "/users")).unwrap();
2048
2049 let m = router.match_path("//users", Method::Get);
2052 assert!(m.is_some());
2053 assert_eq!(m.unwrap().route.path, "/users");
2054 }
2055
2056 #[test]
2057 fn unicode_in_static_path() {
2058 let mut router = Router::new();
2059 router.add(route(Method::Get, "/็จๆท")).unwrap();
2060 router.add(route(Method::Get, "/donnรฉes")).unwrap();
2061
2062 let m = router.match_path("/็จๆท", Method::Get);
2063 assert!(m.is_some());
2064 assert_eq!(m.unwrap().route.path, "/็จๆท");
2065
2066 let m = router.match_path("/donnรฉes", Method::Get);
2067 assert!(m.is_some());
2068 assert_eq!(m.unwrap().route.path, "/donnรฉes");
2069 }
2070
2071 #[test]
2072 fn unicode_in_param_value() {
2073 let mut router = Router::new();
2074 router.add(route(Method::Get, "/users/{name}")).unwrap();
2075
2076 let m = router.match_path("/users/็ฐไธญ", Method::Get);
2077 assert!(m.is_some());
2078 let m = m.unwrap();
2079 assert_eq!(m.params[0], ("name", "็ฐไธญ"));
2080 }
2081
2082 #[test]
2083 fn special_characters_in_param_value() {
2084 let mut router = Router::new();
2085 router.add(route(Method::Get, "/files/{name}")).unwrap();
2086
2087 let m = router.match_path("/files/my-file_v2", Method::Get);
2089 assert!(m.is_some());
2090 assert_eq!(m.unwrap().params[0], ("name", "my-file_v2"));
2091
2092 let m = router.match_path("/files/document.pdf", Method::Get);
2094 assert!(m.is_some());
2095 assert_eq!(m.unwrap().params[0], ("name", "document.pdf"));
2096 }
2097
2098 #[test]
2099 fn empty_param_value() {
2100 let mut router = Router::new();
2101 router.add(route(Method::Get, "/users/{id}/posts")).unwrap();
2102
2103 let m = router.match_path("/users//posts", Method::Get);
2105 assert!(m.is_none());
2107 }
2108
2109 #[test]
2110 fn very_long_path() {
2111 let mut router = Router::new();
2112 let long_path = "/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z";
2113 router.add(route(Method::Get, long_path)).unwrap();
2114
2115 let m = router.match_path(long_path, Method::Get);
2116 assert!(m.is_some());
2117 assert_eq!(m.unwrap().route.path, long_path);
2118 }
2119
2120 #[test]
2121 fn many_routes_same_prefix() {
2122 let mut router = Router::new();
2123 for i in 0..100 {
2124 router
2125 .add(route(Method::Get, &format!("/api/v{}", i)))
2126 .unwrap();
2127 }
2128
2129 assert_eq!(router.routes().len(), 100);
2130
2131 for i in 0..100 {
2133 let path = format!("/api/v{}", i);
2134 let m = router.match_path(&path, Method::Get);
2135 assert!(m.is_some());
2136 assert_eq!(m.unwrap().route.path, path);
2137 }
2138 }
2139
2140 #[test]
2145 fn head_matches_get_route() {
2146 let mut router = Router::new();
2147 router.add(route(Method::Get, "/users")).unwrap();
2148
2149 let m = router.match_path("/users", Method::Head);
2151 assert!(m.is_some());
2152 assert_eq!(m.unwrap().route.method, Method::Get);
2153 }
2154
2155 #[test]
2156 fn head_with_explicit_head_route() {
2157 let mut router = Router::new();
2158 router.add(route(Method::Get, "/users")).unwrap();
2159 router.add(route(Method::Head, "/users")).unwrap();
2160
2161 let m = router.match_path("/users", Method::Head);
2163 assert!(m.is_some());
2164 assert_eq!(m.unwrap().route.method, Method::Head);
2165 }
2166
2167 #[test]
2168 fn head_does_not_match_non_get() {
2169 let mut router = Router::new();
2170 router.add(route(Method::Post, "/users")).unwrap();
2171
2172 let result = router.lookup("/users", Method::Head);
2174 match result {
2175 RouteLookup::MethodNotAllowed { allowed } => {
2176 assert!(!allowed.contains(Method::Head));
2177 assert!(allowed.contains(Method::Post));
2178 }
2179 _ => panic!("expected MethodNotAllowed"),
2180 }
2181 }
2182
2183 #[test]
2188 fn int_converter_edge_cases() {
2189 let mut router = Router::new();
2190 router.add(route(Method::Get, "/items/{id:int}")).unwrap();
2191
2192 let m = router.match_path("/items/0", Method::Get);
2194 assert!(m.is_some());
2195
2196 let m = router.match_path("/items/9223372036854775807", Method::Get);
2198 assert!(m.is_some());
2199
2200 let m = router.match_path("/items/-9223372036854775808", Method::Get);
2202 assert!(m.is_some());
2203
2204 let m = router.match_path("/items/007", Method::Get);
2206 assert!(m.is_some());
2207
2208 let m = router.match_path("/items/+123", Method::Get);
2210 assert!(m.is_some());
2212 }
2213
2214 #[test]
2215 fn float_converter_edge_cases() {
2216 let mut router = Router::new();
2217 router
2218 .add(route(Method::Get, "/values/{val:float}"))
2219 .unwrap();
2220
2221 let m = router.match_path("/values/1e10", Method::Get);
2223 assert!(m.is_some());
2224
2225 let m = router.match_path("/values/1e-10", Method::Get);
2227 assert!(m.is_some());
2228
2229 let m = router.match_path("/values/inf", Method::Get);
2231 assert!(m.is_some());
2232
2233 let m = router.match_path("/values/NaN", Method::Get);
2235 assert!(m.is_some());
2236 }
2237
2238 #[test]
2239 fn uuid_converter_case_sensitivity() {
2240 let mut router = Router::new();
2241 router
2242 .add(route(Method::Get, "/objects/{id:uuid}"))
2243 .unwrap();
2244
2245 let m = router.match_path("/objects/550e8400-e29b-41d4-a716-446655440000", Method::Get);
2247 assert!(m.is_some());
2248
2249 let m = router.match_path("/objects/550E8400-E29B-41D4-A716-446655440000", Method::Get);
2251 assert!(m.is_some());
2252
2253 let m = router.match_path("/objects/550e8400-E29B-41d4-A716-446655440000", Method::Get);
2255 assert!(m.is_some());
2256 }
2257
2258 #[test]
2259 fn uuid_converter_invalid_formats() {
2260 let mut router = Router::new();
2261 router
2262 .add(route(Method::Get, "/objects/{id:uuid}"))
2263 .unwrap();
2264
2265 assert!(
2267 router
2268 .match_path("/objects/550e8400-e29b-41d4-a716-44665544000", Method::Get)
2269 .is_none()
2270 );
2271 assert!(
2272 router
2273 .match_path(
2274 "/objects/550e8400-e29b-41d4-a716-4466554400000",
2275 Method::Get
2276 )
2277 .is_none()
2278 );
2279
2280 assert!(
2282 router
2283 .match_path("/objects/550e8400e29b41d4a716446655440000", Method::Get)
2284 .is_none()
2285 );
2286
2287 assert!(
2289 router
2290 .match_path("/objects/550g8400-e29b-41d4-a716-446655440000", Method::Get)
2291 .is_none()
2292 );
2293 }
2294
2295 #[test]
2296 fn unknown_converter_defaults_to_str() {
2297 let segments = parse_path("/items/{id:custom}");
2298 assert_eq!(segments.len(), 2);
2299 match &segments[1] {
2300 PathSegment::Param { name, converter } => {
2301 assert_eq!(*name, "id");
2302 assert_eq!(*converter, Converter::Str);
2303 }
2304 _ => panic!("Expected param segment"),
2305 }
2306 }
2307
2308 #[test]
2313 fn parse_empty_path() {
2314 let segments = parse_path("");
2315 assert!(segments.is_empty());
2316 }
2317
2318 #[test]
2319 fn parse_root_only() {
2320 let segments = parse_path("/");
2321 assert!(segments.is_empty());
2322 }
2323
2324 #[test]
2325 fn parse_leading_trailing_slashes() {
2326 let segments = parse_path("///users///");
2327 assert_eq!(segments.len(), 1);
2328 match &segments[0] {
2329 PathSegment::Static(s) => assert_eq!(*s, "users"),
2330 _ => panic!("Expected static segment"),
2331 }
2332 }
2333
2334 #[test]
2335 fn parse_param_with_colon_no_type() {
2336 let segments = parse_path("/items/{id:}");
2338 assert_eq!(segments.len(), 2);
2339 match &segments[1] {
2340 PathSegment::Param { name, converter } => {
2341 assert_eq!(*name, "id");
2342 assert_eq!(*converter, Converter::Str);
2344 }
2345 _ => panic!("Expected param segment"),
2346 }
2347 }
2348
2349 #[test]
2354 fn lookup_404_empty_router() {
2355 let router = Router::new();
2356 assert!(matches!(
2357 router.lookup("/anything", Method::Get),
2358 RouteLookup::NotFound
2359 ));
2360 }
2361
2362 #[test]
2363 fn lookup_404_no_matching_path() {
2364 let mut router = Router::new();
2365 router.add(route(Method::Get, "/users")).unwrap();
2366 router.add(route(Method::Get, "/items")).unwrap();
2367
2368 assert!(matches!(
2369 router.lookup("/other", Method::Get),
2370 RouteLookup::NotFound
2371 ));
2372 assert!(matches!(
2373 router.lookup("/user", Method::Get),
2374 RouteLookup::NotFound
2375 )); }
2377
2378 #[test]
2379 fn lookup_404_partial_path_match() {
2380 let mut router = Router::new();
2381 router.add(route(Method::Get, "/api/v1/users")).unwrap();
2382
2383 assert!(matches!(
2385 router.lookup("/api", Method::Get),
2386 RouteLookup::NotFound
2387 ));
2388 assert!(matches!(
2389 router.lookup("/api/v1", Method::Get),
2390 RouteLookup::NotFound
2391 ));
2392 }
2393
2394 #[test]
2395 fn lookup_404_extra_path_segments() {
2396 let mut router = Router::new();
2397 router.add(route(Method::Get, "/users")).unwrap();
2398
2399 assert!(matches!(
2401 router.lookup("/users/extra", Method::Get),
2402 RouteLookup::NotFound
2403 ));
2404 }
2405
2406 #[test]
2407 fn lookup_405_single_method() {
2408 let mut router = Router::new();
2409 router.add(route(Method::Get, "/users")).unwrap();
2410
2411 let result = router.lookup("/users", Method::Post);
2412 match result {
2413 RouteLookup::MethodNotAllowed { allowed } => {
2414 assert_eq!(allowed.methods(), &[Method::Get, Method::Head]);
2415 }
2416 _ => panic!("expected MethodNotAllowed"),
2417 }
2418 }
2419
2420 #[test]
2421 fn lookup_405_all_methods() {
2422 let mut router = Router::new();
2423 router.add(route(Method::Get, "/resource")).unwrap();
2424 router.add(route(Method::Post, "/resource")).unwrap();
2425 router.add(route(Method::Put, "/resource")).unwrap();
2426 router.add(route(Method::Delete, "/resource")).unwrap();
2427 router.add(route(Method::Patch, "/resource")).unwrap();
2428 router.add(route(Method::Options, "/resource")).unwrap();
2429
2430 let result = router.lookup("/resource", Method::Trace);
2431 match result {
2432 RouteLookup::MethodNotAllowed { allowed } => {
2433 let header = allowed.header_value();
2434 assert!(header.contains("GET"));
2435 assert!(header.contains("HEAD"));
2436 assert!(header.contains("POST"));
2437 assert!(header.contains("PUT"));
2438 assert!(header.contains("DELETE"));
2439 assert!(header.contains("PATCH"));
2440 assert!(header.contains("OPTIONS"));
2441 }
2442 _ => panic!("expected MethodNotAllowed"),
2443 }
2444 }
2445
2446 #[test]
2451 fn allowed_methods_deduplication() {
2452 let allowed = AllowedMethods::new(vec![Method::Get, Method::Get, Method::Post]);
2454 assert_eq!(allowed.methods().len(), 3); }
2456
2457 #[test]
2458 fn allowed_methods_sorting() {
2459 let allowed = AllowedMethods::new(vec![Method::Delete, Method::Get, Method::Post]);
2461 assert_eq!(allowed.methods()[0], Method::Get);
2462 assert_eq!(allowed.methods()[1], Method::Head); assert_eq!(allowed.methods()[2], Method::Post);
2464 assert_eq!(allowed.methods()[3], Method::Delete);
2465 }
2466
2467 #[test]
2468 fn allowed_methods_head_not_duplicated() {
2469 let allowed = AllowedMethods::new(vec![Method::Get, Method::Head]);
2471 let count = allowed
2472 .methods()
2473 .iter()
2474 .filter(|&&m| m == Method::Head)
2475 .count();
2476 assert_eq!(count, 1);
2477 }
2478
2479 #[test]
2480 fn allowed_methods_empty() {
2481 let allowed = AllowedMethods::new(vec![]);
2482 assert!(allowed.methods().is_empty());
2483 assert_eq!(allowed.header_value(), "");
2484 }
2485
2486 #[test]
2491 fn wildcard_asterisk_syntax_basic() {
2492 let mut router = Router::new();
2493 router.add(route(Method::Get, "/files/{*path}")).unwrap();
2494
2495 let m = router.match_path("/files/a.txt", Method::Get).unwrap();
2496 assert_eq!(m.params[0], ("path", "a.txt"));
2497 }
2498
2499 #[test]
2500 fn wildcard_asterisk_captures_multiple_segments() {
2501 let mut router = Router::new();
2502 router
2503 .add(route(Method::Get, "/files/{*filepath}"))
2504 .unwrap();
2505
2506 let m = router
2507 .match_path("/files/css/styles/main.css", Method::Get)
2508 .unwrap();
2509 assert_eq!(m.params[0], ("filepath", "css/styles/main.css"));
2510 }
2511
2512 #[test]
2513 fn wildcard_asterisk_with_prefix() {
2514 let mut router = Router::new();
2515 router.add(route(Method::Get, "/api/v1/{*rest}")).unwrap();
2516
2517 let m = router
2518 .match_path("/api/v1/users/123/posts", Method::Get)
2519 .unwrap();
2520 assert_eq!(m.params[0], ("rest", "users/123/posts"));
2521 }
2522
2523 #[test]
2524 fn wildcard_asterisk_empty_capture() {
2525 let mut router = Router::new();
2526 router.add(route(Method::Get, "/files/{*path}")).unwrap();
2527
2528 let m = router.match_path("/files/x", Method::Get).unwrap();
2530 assert_eq!(m.params[0], ("path", "x"));
2531 }
2532
2533 #[test]
2534 fn wildcard_asterisk_must_be_terminal() {
2535 let mut router = Router::new();
2536 let result = router.add(route(Method::Get, "/files/{*path}/edit"));
2537 assert!(matches!(result, Err(RouteAddError::InvalidPath(_))));
2538 }
2539
2540 #[test]
2541 fn wildcard_asterisk_syntax_equivalent_to_path_converter() {
2542 let segments_asterisk = parse_path("/files/{*filepath}");
2544 let segments_converter = parse_path("/files/{filepath:path}");
2545
2546 assert_eq!(segments_asterisk.len(), 2);
2547 assert_eq!(segments_converter.len(), 2);
2548
2549 match (&segments_asterisk[1], &segments_converter[1]) {
2550 (
2551 PathSegment::Param {
2552 name: n1,
2553 converter: c1,
2554 },
2555 PathSegment::Param {
2556 name: n2,
2557 converter: c2,
2558 },
2559 ) => {
2560 assert_eq!(*n1, "filepath");
2561 assert_eq!(*n2, "filepath");
2562 assert_eq!(*c1, Converter::Path);
2563 assert_eq!(*c2, Converter::Path);
2564 }
2565 _ => panic!("Expected param segments"),
2566 }
2567 }
2568
2569 #[test]
2570 fn wildcard_asterisk_spa_routing() {
2571 let mut router = Router::new();
2572 router.add(route(Method::Get, "/api/users")).unwrap();
2574 router.add(route(Method::Get, "/api/posts")).unwrap();
2575 router.add(route(Method::Get, "/{*route}")).unwrap();
2577
2578 let m = router.match_path("/api/users", Method::Get).unwrap();
2580 assert_eq!(m.route.path, "/api/users");
2581
2582 let m = router.match_path("/dashboard", Method::Get).unwrap();
2584 assert_eq!(m.params[0], ("route", "dashboard"));
2585
2586 let m = router
2587 .match_path("/users/123/profile", Method::Get)
2588 .unwrap();
2589 assert_eq!(m.params[0], ("route", "users/123/profile"));
2590 }
2591
2592 #[test]
2593 fn wildcard_asterisk_file_serving() {
2594 let mut router = Router::new();
2595 router
2596 .add(route(Method::Get, "/static/{*filepath}"))
2597 .unwrap();
2598
2599 let m = router
2600 .match_path("/static/js/app.bundle.js", Method::Get)
2601 .unwrap();
2602 assert_eq!(m.params[0], ("filepath", "js/app.bundle.js"));
2603
2604 let m = router
2605 .match_path("/static/images/logo.png", Method::Get)
2606 .unwrap();
2607 assert_eq!(m.params[0], ("filepath", "images/logo.png"));
2608 }
2609
2610 #[test]
2611 fn wildcard_asterisk_priority_lowest() {
2612 let mut router = Router::new();
2613 router.add(route(Method::Get, "/users/me")).unwrap();
2615 router.add(route(Method::Get, "/users/{id}")).unwrap();
2617 router.add(route(Method::Get, "/{*path}")).unwrap();
2619
2620 let m = router.match_path("/users/me", Method::Get).unwrap();
2622 assert_eq!(m.route.path, "/users/me");
2623 assert!(m.params.is_empty());
2624
2625 let m = router.match_path("/users/123", Method::Get).unwrap();
2627 assert_eq!(m.route.path, "/users/{id}");
2628 assert_eq!(m.params[0], ("id", "123"));
2629
2630 let m = router.match_path("/other/deep/path", Method::Get).unwrap();
2632 assert_eq!(m.route.path, "/{*path}");
2633 assert_eq!(m.params[0], ("path", "other/deep/path"));
2634 }
2635
2636 #[test]
2637 fn parse_wildcard_asterisk_syntax() {
2638 let segments = parse_path("/files/{*path}");
2639 assert_eq!(segments.len(), 2);
2640
2641 match &segments[0] {
2642 PathSegment::Static(s) => assert_eq!(*s, "files"),
2643 _ => panic!("Expected static segment"),
2644 }
2645
2646 match &segments[1] {
2647 PathSegment::Param { name, converter } => {
2648 assert_eq!(*name, "path");
2649 assert_eq!(*converter, Converter::Path);
2650 }
2651 _ => panic!("Expected param segment"),
2652 }
2653 }
2654
2655 #[test]
2656 fn wildcard_asterisk_conflict_with_path_converter() {
2657 let mut router = Router::new();
2658 router.add(route(Method::Get, "/files/{*path}")).unwrap();
2659
2660 let result = router.add(route(Method::Get, "/files/{filepath:path}"));
2662 assert!(matches!(result, Err(RouteAddError::Conflict(_))));
2663 }
2664
2665 #[test]
2666 fn wildcard_asterisk_different_methods_no_conflict() {
2667 let mut router = Router::new();
2668 router.add(route(Method::Get, "/files/{*path}")).unwrap();
2669 router.add(route(Method::Post, "/files/{*path}")).unwrap();
2670 router.add(route(Method::Delete, "/files/{*path}")).unwrap();
2671
2672 assert_eq!(router.routes().len(), 3);
2673
2674 let m = router.match_path("/files/a/b/c", Method::Get).unwrap();
2676 assert_eq!(m.route.method, Method::Get);
2677
2678 let m = router.match_path("/files/a/b/c", Method::Post).unwrap();
2679 assert_eq!(m.route.method, Method::Post);
2680
2681 let m = router.match_path("/files/a/b/c", Method::Delete).unwrap();
2682 assert_eq!(m.route.method, Method::Delete);
2683 }
2684
2685 #[test]
2698 fn priority_static_before_param() {
2699 let mut router = Router::new();
2701 router.add(route(Method::Get, "/users/{id}")).unwrap();
2702 router.add(route(Method::Get, "/users/me")).unwrap();
2703
2704 let m = router.match_path("/users/me", Method::Get).unwrap();
2706 assert_eq!(m.route.path, "/users/me");
2707 assert!(m.params.is_empty());
2708
2709 let m = router.match_path("/users/123", Method::Get).unwrap();
2711 assert_eq!(m.route.path, "/users/{id}");
2712 assert_eq!(m.params[0], ("id", "123"));
2713 }
2714
2715 #[test]
2716 fn priority_named_param_vs_wildcard_conflict() {
2717 let mut router = Router::new();
2720 router.add(route(Method::Get, "/files/{name}")).unwrap();
2721
2722 let result = router.add(route(Method::Get, "/files/{*path}"));
2724 assert!(
2725 matches!(result, Err(RouteAddError::Conflict(_))),
2726 "Named param and wildcard at same position should conflict"
2727 );
2728 }
2729
2730 #[test]
2731 fn priority_different_prefixes_no_conflict() {
2732 let mut router = Router::new();
2734 router.add(route(Method::Get, "/files/{name}")).unwrap();
2735 router.add(route(Method::Get, "/static/{*path}")).unwrap();
2736
2737 let m = router.match_path("/files/foo.txt", Method::Get).unwrap();
2739 assert_eq!(m.route.path, "/files/{name}");
2740
2741 let m = router
2743 .match_path("/static/css/main.css", Method::Get)
2744 .unwrap();
2745 assert_eq!(m.route.path, "/static/{*path}");
2746 }
2747
2748 #[test]
2749 fn priority_nested_param_before_shallow_wildcard() {
2750 let mut router = Router::new();
2752 router.add(route(Method::Get, "/{*path}")).unwrap();
2753 router.add(route(Method::Get, "/api/users")).unwrap();
2754
2755 let m = router.match_path("/api/users", Method::Get).unwrap();
2757 assert_eq!(m.route.path, "/api/users");
2758
2759 let m = router.match_path("/other/path", Method::Get).unwrap();
2761 assert_eq!(m.route.path, "/{*path}");
2762 }
2763
2764 #[test]
2765 fn priority_multiple_static_depths() {
2766 let mut router = Router::new();
2768 router.add(route(Method::Get, "/api/{*rest}")).unwrap();
2769 router.add(route(Method::Get, "/api/v1/users")).unwrap();
2770 router
2771 .add(route(Method::Get, "/api/v1/{resource}"))
2772 .unwrap();
2773
2774 let m = router.match_path("/api/v1/users", Method::Get).unwrap();
2776 assert_eq!(m.route.path, "/api/v1/users");
2777
2778 let m = router.match_path("/api/v1/items", Method::Get).unwrap();
2780 assert_eq!(m.route.path, "/api/v1/{resource}");
2781
2782 let m = router
2784 .match_path("/api/v2/anything/deep", Method::Get)
2785 .unwrap();
2786 assert_eq!(m.route.path, "/api/{*rest}");
2787 }
2788
2789 #[test]
2790 fn priority_complex_route_set() {
2791 let mut router = Router::new();
2793
2794 router.add(route(Method::Get, "/users/me")).unwrap();
2796 router
2797 .add(route(Method::Get, "/users/{user_id}/profile"))
2798 .unwrap();
2799 router.add(route(Method::Get, "/users/{user_id}")).unwrap();
2800 router.add(route(Method::Get, "/{*path}")).unwrap();
2801
2802 let m = router.match_path("/users/me", Method::Get).unwrap();
2804 assert_eq!(m.route.path, "/users/me");
2805
2806 let m = router.match_path("/users/123", Method::Get).unwrap();
2808 assert_eq!(m.route.path, "/users/{user_id}");
2809 assert_eq!(m.params[0], ("user_id", "123"));
2810
2811 let m = router
2813 .match_path("/users/123/profile", Method::Get)
2814 .unwrap();
2815 assert_eq!(m.route.path, "/users/{user_id}/profile");
2816 assert_eq!(m.params[0], ("user_id", "123"));
2817
2818 let m = router.match_path("/anything/else", Method::Get).unwrap();
2820 assert_eq!(m.route.path, "/{*path}");
2821 assert_eq!(m.params[0], ("path", "anything/else"));
2822 }
2823
2824 #[test]
2829 fn converter_convert_str() {
2830 let result = Converter::Str.convert("hello", "param");
2831 assert!(result.is_ok());
2832 assert_eq!(result.unwrap(), ParamValue::Str("hello".to_string()));
2833 }
2834
2835 #[test]
2836 fn converter_convert_int_valid() {
2837 let result = Converter::Int.convert("42", "id");
2838 assert!(result.is_ok());
2839 assert_eq!(result.unwrap(), ParamValue::Int(42));
2840 }
2841
2842 #[test]
2843 fn converter_convert_int_negative() {
2844 let result = Converter::Int.convert("-123", "id");
2845 assert!(result.is_ok());
2846 assert_eq!(result.unwrap(), ParamValue::Int(-123));
2847 }
2848
2849 #[test]
2850 fn converter_convert_int_invalid() {
2851 let result = Converter::Int.convert("abc", "id");
2852 assert!(result.is_err());
2853 match result.unwrap_err() {
2854 ConversionError::InvalidInt { value, param } => {
2855 assert_eq!(value, "abc");
2856 assert_eq!(param, "id");
2857 }
2858 _ => panic!("Expected InvalidInt error"),
2859 }
2860 }
2861
2862 #[test]
2863 #[allow(clippy::approx_constant)]
2864 fn converter_convert_float_valid() {
2865 let result = Converter::Float.convert("3.14", "val");
2866 assert!(result.is_ok());
2867 assert_eq!(result.unwrap(), ParamValue::Float(3.14));
2868 }
2869
2870 #[test]
2871 fn converter_convert_float_integer() {
2872 let result = Converter::Float.convert("42", "val");
2873 assert!(result.is_ok());
2874 assert_eq!(result.unwrap(), ParamValue::Float(42.0));
2875 }
2876
2877 #[test]
2878 fn converter_convert_float_scientific() {
2879 let result = Converter::Float.convert("1e10", "val");
2880 assert!(result.is_ok());
2881 assert_eq!(result.unwrap(), ParamValue::Float(1e10));
2882 }
2883
2884 #[test]
2885 fn converter_convert_float_invalid() {
2886 let result = Converter::Float.convert("not-a-float", "val");
2887 assert!(result.is_err());
2888 match result.unwrap_err() {
2889 ConversionError::InvalidFloat { value, param } => {
2890 assert_eq!(value, "not-a-float");
2891 assert_eq!(param, "val");
2892 }
2893 _ => panic!("Expected InvalidFloat error"),
2894 }
2895 }
2896
2897 #[test]
2898 fn converter_convert_uuid_valid() {
2899 let result = Converter::Uuid.convert("550e8400-e29b-41d4-a716-446655440000", "id");
2900 assert!(result.is_ok());
2901 assert_eq!(
2902 result.unwrap(),
2903 ParamValue::Uuid("550e8400-e29b-41d4-a716-446655440000".to_string())
2904 );
2905 }
2906
2907 #[test]
2908 fn converter_convert_uuid_invalid() {
2909 let result = Converter::Uuid.convert("not-a-uuid", "id");
2910 assert!(result.is_err());
2911 match result.unwrap_err() {
2912 ConversionError::InvalidUuid { value, param } => {
2913 assert_eq!(value, "not-a-uuid");
2914 assert_eq!(param, "id");
2915 }
2916 _ => panic!("Expected InvalidUuid error"),
2917 }
2918 }
2919
2920 #[test]
2921 fn converter_convert_path() {
2922 let result = Converter::Path.convert("a/b/c.txt", "filepath");
2923 assert!(result.is_ok());
2924 assert_eq!(result.unwrap(), ParamValue::Path("a/b/c.txt".to_string()));
2925 }
2926
2927 #[test]
2928 fn param_value_accessors() {
2929 let val = ParamValue::Str("hello".to_string());
2931 assert_eq!(val.as_str(), "hello");
2932 assert_eq!(val.as_int(), None);
2933 assert_eq!(val.as_float(), None);
2934 assert_eq!(val.into_string(), Some("hello".to_string()));
2935
2936 let val = ParamValue::Int(42);
2938 assert_eq!(val.as_int(), Some(42));
2939 assert_eq!(val.as_float(), None);
2940 assert_eq!(val.into_string(), None);
2941
2942 #[allow(clippy::approx_constant)]
2944 let val = ParamValue::Float(3.14);
2945 #[allow(clippy::approx_constant)]
2946 let expected_pi = Some(3.14);
2947 assert_eq!(val.as_float(), expected_pi);
2948 assert_eq!(val.as_int(), None);
2949 assert_eq!(val.into_string(), None);
2950
2951 let val = ParamValue::Uuid("550e8400-e29b-41d4-a716-446655440000".to_string());
2953 assert_eq!(val.as_str(), "550e8400-e29b-41d4-a716-446655440000");
2954 assert_eq!(
2955 val.into_string(),
2956 Some("550e8400-e29b-41d4-a716-446655440000".to_string())
2957 );
2958
2959 let val = ParamValue::Path("a/b/c".to_string());
2961 assert_eq!(val.as_str(), "a/b/c");
2962 assert_eq!(val.into_string(), Some("a/b/c".to_string()));
2963 }
2964
2965 #[test]
2966 fn conversion_error_display() {
2967 let err = ConversionError::InvalidInt {
2968 value: "abc".to_string(),
2969 param: "id".to_string(),
2970 };
2971 let msg = format!("{}", err);
2972 assert!(msg.contains("id"));
2973 assert!(msg.contains("abc"));
2974 assert!(msg.contains("integer"));
2975
2976 let err = ConversionError::InvalidFloat {
2977 value: "xyz".to_string(),
2978 param: "val".to_string(),
2979 };
2980 let msg = format!("{}", err);
2981 assert!(msg.contains("val"));
2982 assert!(msg.contains("xyz"));
2983 assert!(msg.contains("float"));
2984
2985 let err = ConversionError::InvalidUuid {
2986 value: "bad".to_string(),
2987 param: "uuid".to_string(),
2988 };
2989 let msg = format!("{}", err);
2990 assert!(msg.contains("uuid"));
2991 assert!(msg.contains("bad"));
2992 assert!(msg.contains("UUID"));
2993 }
2994
2995 #[test]
2996 fn converter_type_name() {
2997 assert_eq!(Converter::Str.type_name(), "string");
2998 assert_eq!(Converter::Int.type_name(), "integer");
2999 assert_eq!(Converter::Float.type_name(), "float");
3000 assert_eq!(Converter::Uuid.type_name(), "UUID");
3001 assert_eq!(Converter::Path.type_name(), "path");
3002 }
3003
3004 #[test]
3005 fn route_match_typed_getters() {
3006 let mut router = Router::new();
3007 router
3008 .add(route(Method::Get, "/items/{id:int}/price/{val:float}"))
3009 .unwrap();
3010
3011 let m = router
3012 .match_path("/items/42/price/99.99", Method::Get)
3013 .unwrap();
3014
3015 assert_eq!(m.get_param("id"), Some("42"));
3017 assert_eq!(m.get_param("val"), Some("99.99"));
3018
3019 assert_eq!(m.get_param_int("id"), Some(Ok(42)));
3021 assert_eq!(m.get_param_float("val"), Some(Ok(99.99)));
3022
3023 assert!(m.get_param_int("missing").is_none());
3025
3026 let result = m.get_param_int("val");
3028 assert!(result.is_some());
3031 assert!(result.unwrap().is_err());
3032 }
3033
3034 #[test]
3035 fn route_match_param_count() {
3036 let mut router = Router::new();
3037 router
3038 .add(route(Method::Get, "/users/{user_id}/posts/{post_id}"))
3039 .unwrap();
3040
3041 let m = router.match_path("/users/1/posts/2", Method::Get).unwrap();
3042
3043 assert_eq!(m.param_count(), 2);
3044 assert!(!m.is_empty());
3045
3046 let mut router2 = Router::new();
3048 router2.add(route(Method::Get, "/static")).unwrap();
3049 let m2 = router2.match_path("/static", Method::Get).unwrap();
3050 assert_eq!(m2.param_count(), 0);
3051 assert!(m2.is_empty());
3052 }
3053
3054 #[test]
3055 fn route_match_iter() {
3056 let mut router = Router::new();
3057 router
3058 .add(route(Method::Get, "/a/{x}/b/{y}/c/{z}"))
3059 .unwrap();
3060
3061 let m = router.match_path("/a/1/b/2/c/3", Method::Get).unwrap();
3062
3063 let params: Vec<_> = m.iter().collect();
3064 assert_eq!(params.len(), 3);
3065 assert_eq!(params[0], ("x", "1"));
3066 assert_eq!(params[1], ("y", "2"));
3067 assert_eq!(params[2], ("z", "3"));
3068 }
3069
3070 #[test]
3071 fn route_match_is_param_uuid() {
3072 let mut router = Router::new();
3073 router
3074 .add(route(Method::Get, "/objects/{id:uuid}"))
3075 .unwrap();
3076
3077 let m = router
3078 .match_path("/objects/550e8400-e29b-41d4-a716-446655440000", Method::Get)
3079 .unwrap();
3080
3081 assert_eq!(m.is_param_uuid("id"), Some(true));
3082 assert_eq!(m.is_param_uuid("missing"), None);
3083 }
3084
3085 #[test]
3086 fn route_match_integer_variants() {
3087 let mut router = Router::new();
3088 router.add(route(Method::Get, "/items/{id}")).unwrap();
3089
3090 let m = router.match_path("/items/12345", Method::Get).unwrap();
3091
3092 assert_eq!(m.get_param_int("id"), Some(Ok(12345i64)));
3094 assert_eq!(m.get_param_i32("id"), Some(Ok(12345i32)));
3095 assert_eq!(m.get_param_u64("id"), Some(Ok(12345u64)));
3096 assert_eq!(m.get_param_u32("id"), Some(Ok(12345u32)));
3097
3098 assert_eq!(m.get_param_float("id"), Some(Ok(12345.0f64)));
3100 assert_eq!(m.get_param_f32("id"), Some(Ok(12345.0f32)));
3101 }
3102
3103 #[test]
3108 fn mount_basic() {
3109 let mut child = Router::new();
3110 child.add(route(Method::Get, "/users")).unwrap();
3111 child.add(route(Method::Get, "/items")).unwrap();
3112
3113 let parent = Router::new().mount("/api/v1", child).unwrap();
3114
3115 let m = parent.match_path("/api/v1/users", Method::Get).unwrap();
3117 assert_eq!(m.route.path, "/api/v1/users");
3118
3119 let m = parent.match_path("/api/v1/items", Method::Get).unwrap();
3120 assert_eq!(m.route.path, "/api/v1/items");
3121 }
3122
3123 #[test]
3124 fn mount_with_params() {
3125 let mut child = Router::new();
3126 child.add(route(Method::Get, "/users/{id}")).unwrap();
3127 child
3128 .add(route(Method::Get, "/users/{id}/posts/{post_id}"))
3129 .unwrap();
3130
3131 let parent = Router::new().mount("/api", child).unwrap();
3132
3133 let m = parent.match_path("/api/users/42", Method::Get).unwrap();
3135 assert_eq!(m.route.path, "/api/users/{id}");
3136 assert_eq!(m.params[0], ("id", "42"));
3137
3138 let m = parent
3139 .match_path("/api/users/1/posts/99", Method::Get)
3140 .unwrap();
3141 assert_eq!(m.params.len(), 2);
3142 assert_eq!(m.params[0], ("id", "1"));
3143 assert_eq!(m.params[1], ("post_id", "99"));
3144 }
3145
3146 #[test]
3147 fn mount_preserves_methods() {
3148 let mut child = Router::new();
3149 child.add(route(Method::Get, "/resource")).unwrap();
3150 child.add(route(Method::Post, "/resource")).unwrap();
3151 child.add(route(Method::Delete, "/resource")).unwrap();
3152
3153 let parent = Router::new().mount("/api", child).unwrap();
3154
3155 let m = parent.match_path("/api/resource", Method::Get).unwrap();
3157 assert_eq!(m.route.method, Method::Get);
3158
3159 let m = parent.match_path("/api/resource", Method::Post).unwrap();
3160 assert_eq!(m.route.method, Method::Post);
3161
3162 let m = parent.match_path("/api/resource", Method::Delete).unwrap();
3163 assert_eq!(m.route.method, Method::Delete);
3164 }
3165
3166 #[test]
3167 fn mount_root_route() {
3168 let mut child = Router::new();
3169 child.add(route(Method::Get, "/")).unwrap();
3170
3171 let parent = Router::new().mount("/api", child).unwrap();
3172
3173 let m = parent.match_path("/api", Method::Get).unwrap();
3175 assert_eq!(m.route.path, "/api");
3176 }
3177
3178 #[test]
3179 fn mount_trailing_slash_prefix() {
3180 let mut child = Router::new();
3181 child.add(route(Method::Get, "/users")).unwrap();
3182
3183 let parent = Router::new().mount("/api/", child).unwrap();
3185
3186 let m = parent.match_path("/api/users", Method::Get).unwrap();
3187 assert_eq!(m.route.path, "/api/users");
3188 }
3189
3190 #[test]
3191 fn mount_empty_prefix() {
3192 let mut child = Router::new();
3193 child.add(route(Method::Get, "/users")).unwrap();
3194
3195 let parent = Router::new().mount("", child).unwrap();
3196
3197 let m = parent.match_path("/users", Method::Get).unwrap();
3198 assert_eq!(m.route.path, "/users");
3199 }
3200
3201 #[test]
3202 fn mount_nested() {
3203 let mut inner = Router::new();
3205 inner.add(route(Method::Get, "/items")).unwrap();
3206
3207 let middle = Router::new().mount("/v1", inner).unwrap();
3209
3210 let outer = Router::new().mount("/api", middle).unwrap();
3212
3213 let m = outer.match_path("/api/v1/items", Method::Get).unwrap();
3215 assert_eq!(m.route.path, "/api/v1/items");
3216 }
3217
3218 #[test]
3219 fn mount_conflict_detection() {
3220 let mut child1 = Router::new();
3221 child1.add(route(Method::Get, "/users")).unwrap();
3222
3223 let mut child2 = Router::new();
3224 child2.add(route(Method::Get, "/users")).unwrap();
3225
3226 let parent = Router::new().mount("/api", child1).unwrap();
3227
3228 let result = parent.mount("/api", child2);
3230 assert!(matches!(result, Err(RouteAddError::Conflict(_))));
3231 }
3232
3233 #[test]
3234 fn mount_no_conflict_different_prefixes() {
3235 let mut child1 = Router::new();
3236 child1.add(route(Method::Get, "/users")).unwrap();
3237
3238 let mut child2 = Router::new();
3239 child2.add(route(Method::Get, "/users")).unwrap();
3240
3241 let parent = Router::new()
3242 .mount("/api/v1", child1)
3243 .unwrap()
3244 .mount("/api/v2", child2)
3245 .unwrap();
3246
3247 let m = parent.match_path("/api/v1/users", Method::Get).unwrap();
3249 assert_eq!(m.route.path, "/api/v1/users");
3250
3251 let m = parent.match_path("/api/v2/users", Method::Get).unwrap();
3252 assert_eq!(m.route.path, "/api/v2/users");
3253 }
3254
3255 #[test]
3256 #[should_panic(expected = "route conflict when nesting router")]
3257 fn nest_panics_on_conflict() {
3258 let mut child1 = Router::new();
3259 child1.add(route(Method::Get, "/users")).unwrap();
3260
3261 let mut child2 = Router::new();
3262 child2.add(route(Method::Get, "/users")).unwrap();
3263
3264 let parent = Router::new().nest("/api", child1);
3265
3266 let _ = parent.nest("/api", child2);
3268 }
3269
3270 #[test]
3271 fn mount_with_wildcard() {
3272 let mut child = Router::new();
3273 child.add(route(Method::Get, "/files/{*path}")).unwrap();
3274
3275 let parent = Router::new().mount("/static", child).unwrap();
3276
3277 let m = parent
3279 .match_path("/static/files/css/style.css", Method::Get)
3280 .unwrap();
3281 assert_eq!(m.route.path, "/static/files/{*path}");
3282 assert_eq!(m.params[0], ("path", "css/style.css"));
3283 }
3284
3285 #[test]
3286 fn mount_parent_and_child_routes() {
3287 let mut parent = Router::new();
3288 parent.add(route(Method::Get, "/health")).unwrap();
3289
3290 let mut child = Router::new();
3291 child.add(route(Method::Get, "/users")).unwrap();
3292
3293 let app = parent.mount("/api", child).unwrap();
3294
3295 let m = app.match_path("/health", Method::Get).unwrap();
3297 assert_eq!(m.route.path, "/health");
3298
3299 let m = app.match_path("/api/users", Method::Get).unwrap();
3300 assert_eq!(m.route.path, "/api/users");
3301 }
3302
3303 #[test]
3320 fn percent_encoded_space_in_static_path() {
3321 let mut router = Router::new();
3322 router.add(route(Method::Get, "/hello%20world")).unwrap();
3323
3324 let m = router.match_path("/hello%20world", Method::Get);
3326 assert!(m.is_some());
3327 assert_eq!(m.unwrap().route.path, "/hello%20world");
3328
3329 let m = router.match_path("/hello world", Method::Get);
3331 assert!(m.is_none());
3332 }
3333
3334 #[test]
3335 fn percent_encoded_slash_in_param() {
3336 let mut router = Router::new();
3337 router.add(route(Method::Get, "/files/{name}")).unwrap();
3338
3339 let m = router.match_path("/files/a%2Fb.txt", Method::Get);
3341 assert!(m.is_some());
3342 assert_eq!(m.unwrap().params[0], ("name", "a%2Fb.txt"));
3343 }
3344
3345 #[test]
3346 fn percent_encoded_special_chars_in_param() {
3347 let mut router = Router::new();
3348 router.add(route(Method::Get, "/search/{query}")).unwrap();
3349
3350 let test_cases = vec![
3352 ("/search/hello%20world", ("query", "hello%20world")),
3353 ("/search/foo%26bar", ("query", "foo%26bar")), ("/search/a%3Db", ("query", "a%3Db")), ("/search/%23hash", ("query", "%23hash")), ("/search/100%25", ("query", "100%25")), ];
3358
3359 for (path, expected) in test_cases {
3360 let m = router.match_path(path, Method::Get);
3361 assert!(m.is_some(), "Failed to match: {}", path);
3362 assert_eq!(m.unwrap().params[0], expected);
3363 }
3364 }
3365
3366 #[test]
3367 fn percent_encoded_unicode_in_param() {
3368 let mut router = Router::new();
3369 router.add(route(Method::Get, "/users/{name}")).unwrap();
3370
3371 let m = router.match_path("/users/%E6%97%A5%E6%9C%AC", Method::Get);
3373 assert!(m.is_some());
3374 assert_eq!(m.unwrap().params[0], ("name", "%E6%97%A5%E6%9C%AC"));
3375 }
3376
3377 #[test]
3378 fn percent_encoded_in_wildcard() {
3379 let mut router = Router::new();
3380 router.add(route(Method::Get, "/files/{*path}")).unwrap();
3381
3382 let m = router.match_path("/files/dir%20name/file%20name.txt", Method::Get);
3384 assert!(m.is_some());
3385 assert_eq!(m.unwrap().params[0], ("path", "dir%20name/file%20name.txt"));
3386 }
3387
3388 #[test]
3389 fn double_percent_encoding() {
3390 let mut router = Router::new();
3391 router.add(route(Method::Get, "/data/{value}")).unwrap();
3392
3393 let m = router.match_path("/data/%2520", Method::Get);
3395 assert!(m.is_some());
3396 assert_eq!(m.unwrap().params[0], ("value", "%2520"));
3397 }
3398
3399 #[test]
3404 fn trailing_slash_strict_mode_static() {
3405 let mut router = Router::new();
3406 router.add(route(Method::Get, "/users")).unwrap();
3407 router.add(route(Method::Get, "/items/")).unwrap();
3408
3409 let m = router.match_path("/users", Method::Get);
3411 assert!(m.is_some());
3412 assert_eq!(m.unwrap().route.path, "/users");
3413
3414 let m = router.match_path("/users/", Method::Get);
3418 if let Some(m) = m {
3419 assert!(m.route.path == "/users" || m.route.path == "/users/");
3421 }
3422
3423 let m = router.match_path("/items/", Method::Get);
3425 assert!(m.is_some());
3426 }
3427
3428 #[test]
3429 fn trailing_slash_on_param_routes() {
3430 let mut router = Router::new();
3431 router.add(route(Method::Get, "/users/{id}")).unwrap();
3432
3433 let m = router.match_path("/users/123", Method::Get);
3435 assert!(m.is_some());
3436 assert_eq!(m.unwrap().params[0], ("id", "123"));
3437
3438 let m = router.match_path("/users/123/", Method::Get);
3440 if let Some(m) = m {
3442 assert_eq!(m.params[0].0, "id");
3443 }
3444 }
3445
3446 #[test]
3447 fn trailing_slash_on_nested_routes() {
3448 let mut router = Router::new();
3449 router.add(route(Method::Get, "/api/v1/users")).unwrap();
3450
3451 let result = router.add(route(Method::Get, "/api/v1/users/"));
3455 assert!(
3456 matches!(result, Err(RouteAddError::Conflict(_))),
3457 "Routes with and without trailing slash should conflict"
3458 );
3459
3460 assert_eq!(router.routes().len(), 1);
3462 }
3463
3464 #[test]
3465 fn multiple_trailing_slashes() {
3466 let mut router = Router::new();
3467 router.add(route(Method::Get, "/data")).unwrap();
3468
3469 let m = router.match_path("/data//", Method::Get);
3471 assert!(m.is_some()); let m = router.match_path("/data///", Method::Get);
3474 assert!(m.is_some()); }
3476
3477 #[test]
3482 fn empty_segment_normalization() {
3483 let mut router = Router::new();
3484 router.add(route(Method::Get, "/a/b/c")).unwrap();
3485
3486 let paths = vec!["/a//b/c", "/a/b//c", "//a/b/c", "/a/b/c//", "//a//b//c//"];
3488
3489 for path in paths {
3490 let m = router.match_path(path, Method::Get);
3491 assert!(m.is_some(), "Failed to match normalized path: {}", path);
3492 assert_eq!(m.unwrap().route.path, "/a/b/c");
3493 }
3494 }
3495
3496 #[test]
3497 fn empty_segment_in_middle_of_params() {
3498 let mut router = Router::new();
3499 router.add(route(Method::Get, "/a/{x}/b/{y}")).unwrap();
3500
3501 let m = router.match_path("/a//1/b/2", Method::Get);
3503 if let Some(m) = m {
3507 assert!(!m.params.is_empty());
3508 }
3509 }
3510
3511 #[test]
3512 fn only_slashes_path() {
3513 let mut router = Router::new();
3514 router.add(route(Method::Get, "/")).unwrap();
3515
3516 let paths = vec!["/", "//", "///", "////"];
3518 for path in paths {
3519 let m = router.match_path(path, Method::Get);
3520 assert!(m.is_some(), "Failed to match root with: {}", path);
3521 }
3522 }
3523
3524 #[test]
3525 fn empty_path_handling() {
3526 let mut router = Router::new();
3527 router.add(route(Method::Get, "/")).unwrap();
3528
3529 let m = router.match_path("", Method::Get);
3531 let _matched = m.is_some();
3534 }
3535
3536 #[test]
3541 fn deep_nesting_50_levels() {
3542 let mut router = Router::new();
3543
3544 let path = format!(
3546 "/{}",
3547 (0..50)
3548 .map(|i| format!("l{}", i))
3549 .collect::<Vec<_>>()
3550 .join("/")
3551 );
3552 router.add(route(Method::Get, &path)).unwrap();
3553
3554 let m = router.match_path(&path, Method::Get);
3556 assert!(m.is_some());
3557 assert_eq!(m.unwrap().route.path, path);
3558 }
3559
3560 #[test]
3561 fn deep_nesting_100_levels() {
3562 let mut router = Router::new();
3563
3564 let path = format!(
3566 "/{}",
3567 (0..100)
3568 .map(|i| format!("d{}", i))
3569 .collect::<Vec<_>>()
3570 .join("/")
3571 );
3572 router.add(route(Method::Get, &path)).unwrap();
3573
3574 let m = router.match_path(&path, Method::Get);
3575 assert!(m.is_some());
3576 assert_eq!(m.unwrap().route.path, path);
3577 }
3578
3579 #[test]
3580 fn deep_nesting_with_params_at_various_depths() {
3581 let mut router = Router::new();
3582
3583 let mut segments = vec![];
3585 for i in 0..20 {
3586 if i == 5 || i == 10 || i == 15 {
3587 segments.push(format!("{{p{}}}", i));
3588 } else {
3589 segments.push(format!("s{}", i));
3590 }
3591 }
3592 let path = format!("/{}", segments.join("/"));
3593 router.add(route(Method::Get, &path)).unwrap();
3594
3595 let mut request_segments = vec![];
3597 for i in 0..20 {
3598 if i == 5 || i == 10 || i == 15 {
3599 request_segments.push(format!("val{}", i));
3600 } else {
3601 request_segments.push(format!("s{}", i));
3602 }
3603 }
3604 let request_path = format!("/{}", request_segments.join("/"));
3605
3606 let m = router.match_path(&request_path, Method::Get);
3607 assert!(m.is_some());
3608 let m = m.unwrap();
3609 assert_eq!(m.params.len(), 3);
3610 assert_eq!(m.params[0], ("p5", "val5"));
3611 assert_eq!(m.params[1], ("p10", "val10"));
3612 assert_eq!(m.params[2], ("p15", "val15"));
3613 }
3614
3615 #[test]
3616 fn deep_nesting_with_wildcard_at_end() {
3617 let mut router = Router::new();
3618
3619 let segments: Vec<_> = (0..30).map(|i| format!("x{}", i)).collect();
3621 let prefix = format!("/{}", segments.join("/"));
3622 let path = format!("{}/{{*rest}}", prefix);
3623 router.add(route(Method::Get, &path)).unwrap();
3624
3625 let request_path = format!("{}/a/b/c/d/e", prefix);
3627 let m = router.match_path(&request_path, Method::Get);
3628 assert!(m.is_some());
3629 assert_eq!(m.unwrap().params[0], ("rest", "a/b/c/d/e"));
3630 }
3631
3632 #[test]
3637 fn many_siblings_500_routes() {
3638 let mut router = Router::new();
3639
3640 for i in 0..500 {
3642 router
3643 .add(route(Method::Get, &format!("/api/endpoint{}", i)))
3644 .unwrap();
3645 }
3646
3647 assert_eq!(router.routes().len(), 500);
3648
3649 for i in [0, 50, 100, 250, 499] {
3651 let path = format!("/api/endpoint{}", i);
3652 let m = router.match_path(&path, Method::Get);
3653 assert!(m.is_some(), "Failed to match: {}", path);
3654 assert_eq!(m.unwrap().route.path, path);
3655 }
3656 }
3657
3658 #[test]
3659 fn many_siblings_with_shared_prefix() {
3660 let mut router = Router::new();
3661
3662 for i in 0..200 {
3664 router
3665 .add(route(Method::Get, &format!("/users/user{:04}", i)))
3666 .unwrap();
3667 }
3668
3669 assert_eq!(router.routes().len(), 200);
3670
3671 for i in [0, 50, 100, 150, 199] {
3673 let path = format!("/users/user{:04}", i);
3674 let m = router.match_path(&path, Method::Get);
3675 assert!(m.is_some());
3676 assert_eq!(m.unwrap().route.path, path);
3677 }
3678 }
3679
3680 #[test]
3681 fn many_siblings_mixed_static_and_param() {
3682 let mut router = Router::new();
3683
3684 for i in 0..100 {
3686 router
3687 .add(route(Method::Get, &format!("/items/item{}", i)))
3688 .unwrap();
3689 }
3690
3691 router.add(route(Method::Get, "/items/{id}")).unwrap();
3693
3694 assert_eq!(router.routes().len(), 101);
3695
3696 let m = router.match_path("/items/item50", Method::Get).unwrap();
3698 assert_eq!(m.route.path, "/items/item50");
3699
3700 let m = router.match_path("/items/other", Method::Get).unwrap();
3702 assert_eq!(m.route.path, "/items/{id}");
3703 assert_eq!(m.params[0], ("id", "other"));
3704 }
3705
3706 #[test]
3707 fn many_siblings_different_methods() {
3708 let mut router = Router::new();
3709
3710 let methods = vec![
3712 Method::Get,
3713 Method::Post,
3714 Method::Put,
3715 Method::Delete,
3716 Method::Patch,
3717 ];
3718
3719 for i in 0..50 {
3720 for method in &methods {
3721 router
3722 .add(Route::new(*method, &format!("/resource{}", i)))
3723 .unwrap();
3724 }
3725 }
3726
3727 assert_eq!(router.routes().len(), 250);
3728
3729 let m = router.match_path("/resource25", Method::Get).unwrap();
3731 assert_eq!(m.route.method, Method::Get);
3732
3733 let m = router.match_path("/resource25", Method::Post).unwrap();
3734 assert_eq!(m.route.method, Method::Post);
3735
3736 let m = router.match_path("/resource25", Method::Delete).unwrap();
3737 assert_eq!(m.route.method, Method::Delete);
3738 }
3739
3740 #[test]
3741 fn stress_wide_and_deep() {
3742 let mut router = Router::new();
3743
3744 for a in 0..10 {
3747 for b in 0..10 {
3748 for c in 0..10 {
3749 let path = format!("/a{}/b{}/c{}", a, b, c);
3750 router.add(route(Method::Get, &path)).unwrap();
3751 }
3752 }
3753 }
3754
3755 assert_eq!(router.routes().len(), 1000);
3756
3757 let m = router.match_path("/a0/b0/c0", Method::Get).unwrap();
3759 assert_eq!(m.route.path, "/a0/b0/c0");
3760
3761 let m = router.match_path("/a5/b5/c5", Method::Get).unwrap();
3762 assert_eq!(m.route.path, "/a5/b5/c5");
3763
3764 let m = router.match_path("/a9/b9/c9", Method::Get).unwrap();
3765 assert_eq!(m.route.path, "/a9/b9/c9");
3766
3767 assert!(router.match_path("/a10/b0/c0", Method::Get).is_none());
3769 assert!(router.match_path("/a0/b10/c0", Method::Get).is_none());
3770 }
3771
3772 #[test]
3777 fn unicode_emoji_in_path() {
3778 let mut router = Router::new();
3779 router.add(route(Method::Get, "/emoji/๐")).unwrap();
3780
3781 let m = router.match_path("/emoji/๐", Method::Get);
3782 assert!(m.is_some());
3783 assert_eq!(m.unwrap().route.path, "/emoji/๐");
3784 }
3785
3786 #[test]
3787 fn unicode_rtl_characters() {
3788 let mut router = Router::new();
3789 router.add(route(Method::Get, "/greet/ู
ุฑุญุจุง")).unwrap();
3791
3792 let m = router.match_path("/greet/ู
ุฑุญุจุง", Method::Get);
3793 assert!(m.is_some());
3794 assert_eq!(m.unwrap().route.path, "/greet/ู
ุฑุญุจุง");
3795 }
3796
3797 #[test]
3798 fn unicode_mixed_scripts() {
3799 let mut router = Router::new();
3800 router
3802 .add(route(Method::Get, "/mix/helloไธ็ะัะธะฒะตั"))
3803 .unwrap();
3804
3805 let m = router.match_path("/mix/helloไธ็ะัะธะฒะตั", Method::Get);
3806 assert!(m.is_some());
3807 }
3808
3809 #[test]
3810 fn unicode_normalization_awareness() {
3811 let mut router = Router::new();
3812 router.add(route(Method::Get, "/cafรฉ")).unwrap();
3814
3815 let m = router.match_path("/cafรฉ", Method::Get);
3817 assert!(m.is_some());
3818
3819 }
3822
3823 #[test]
3824 fn unicode_in_param_with_converter() {
3825 let mut router = Router::new();
3826 router.add(route(Method::Get, "/data/{value:str}")).unwrap();
3827
3828 let m = router.match_path("/data/ๆฅๆฌ่ชใในใ", Method::Get);
3830 assert!(m.is_some());
3831 assert_eq!(m.unwrap().params[0], ("value", "ๆฅๆฌ่ชใในใ"));
3832 }
3833
3834 #[test]
3839 fn int_converter_overflow() {
3840 let mut router = Router::new();
3841 router.add(route(Method::Get, "/id/{num:int}")).unwrap();
3842
3843 let overflow = "99999999999999999999999999999";
3845 let path = format!("/id/{}", overflow);
3846 let m = router.match_path(&path, Method::Get);
3847 assert!(m.is_none());
3848 }
3849
3850 #[test]
3851 fn float_converter_very_small() {
3852 let mut router = Router::new();
3853 router.add(route(Method::Get, "/val/{v:float}")).unwrap();
3854
3855 let m = router.match_path("/val/1e-308", Method::Get);
3857 assert!(m.is_some());
3858 }
3859
3860 #[test]
3861 fn float_converter_very_large() {
3862 let mut router = Router::new();
3863 router.add(route(Method::Get, "/val/{v:float}")).unwrap();
3864
3865 let m = router.match_path("/val/1e308", Method::Get);
3867 assert!(m.is_some());
3868 }
3869
3870 #[test]
3871 fn uuid_converter_nil_uuid() {
3872 let mut router = Router::new();
3873 router.add(route(Method::Get, "/obj/{id:uuid}")).unwrap();
3874
3875 let m = router.match_path("/obj/00000000-0000-0000-0000-000000000000", Method::Get);
3877 assert!(m.is_some());
3878 }
3879
3880 #[test]
3881 fn uuid_converter_max_uuid() {
3882 let mut router = Router::new();
3883 router.add(route(Method::Get, "/obj/{id:uuid}")).unwrap();
3884
3885 let m = router.match_path("/obj/ffffffff-ffff-ffff-ffff-ffffffffffff", Method::Get);
3887 assert!(m.is_some());
3888 }
3889
3890 #[test]
3895 fn path_with_dots() {
3896 let mut router = Router::new();
3897 router.add(route(Method::Get, "/files/{name}")).unwrap();
3898
3899 let m = router.match_path("/files/file.name.ext", Method::Get);
3901 assert!(m.is_some());
3902 assert_eq!(m.unwrap().params[0], ("name", "file.name.ext"));
3903 }
3904
3905 #[test]
3906 fn path_with_only_special_chars() {
3907 let mut router = Router::new();
3908 router.add(route(Method::Get, "/data/{val}")).unwrap();
3909
3910 let m = router.match_path("/data/-._~", Method::Get);
3912 assert!(m.is_some());
3913 assert_eq!(m.unwrap().params[0], ("val", "-._~"));
3914 }
3915
3916 #[test]
3917 fn path_segment_with_colon() {
3918 let mut router = Router::new();
3919 router.add(route(Method::Get, "/time/{val}")).unwrap();
3920
3921 let m = router.match_path("/time/12:30:45", Method::Get);
3923 assert!(m.is_some());
3924 assert_eq!(m.unwrap().params[0], ("val", "12:30:45"));
3925 }
3926
3927 #[test]
3928 fn path_segment_with_at_sign() {
3929 let mut router = Router::new();
3930 router.add(route(Method::Get, "/user/{handle}")).unwrap();
3931
3932 let m = router.match_path("/user/@username", Method::Get);
3934 assert!(m.is_some());
3935 assert_eq!(m.unwrap().params[0], ("handle", "@username"));
3936 }
3937
3938 #[test]
3939 fn very_long_segment() {
3940 let mut router = Router::new();
3941 router.add(route(Method::Get, "/data/{val}")).unwrap();
3942
3943 let long_val: String = (0..1000).map(|_| 'x').collect();
3945 let path = format!("/data/{}", long_val);
3946
3947 let m = router.match_path(&path, Method::Get);
3948 assert!(m.is_some());
3949 assert_eq!(m.unwrap().params[0].1.len(), 1000);
3950 }
3951
3952 #[test]
3953 fn very_long_path_total() {
3954 let mut router = Router::new();
3955
3956 let segments: Vec<_> = (0..500).map(|i| format!("s{}", i)).collect();
3958 let path = format!("/{}", segments.join("/"));
3959 router.add(route(Method::Get, &path)).unwrap();
3960
3961 let m = router.match_path(&path, Method::Get);
3962 assert!(m.is_some());
3963 }
3964
3965 #[test]
3973 fn sibling_params_with_different_names_are_both_reachable() {
3974 let mut router = Router::new();
3975 router
3976 .add(route(Method::Get, "/docs/{venue}/{issuer}/list"))
3977 .unwrap();
3978 router.add(route(Method::Get, "/docs/{key}/body")).unwrap();
3979 router
3980 .add(route(Method::Get, "/docs/{key}/body/sections"))
3981 .unwrap();
3982
3983 let m = router
3984 .match_path("/docs/asx/SKS/list", Method::Get)
3985 .unwrap();
3986 assert_eq!(m.route.path, "/docs/{venue}/{issuer}/list");
3987 assert_eq!(m.params, vec![("venue", "asx"), ("issuer", "SKS")]);
3988
3989 let m = router.match_path("/docs/abc123/body", Method::Get).unwrap();
3990 assert_eq!(m.route.path, "/docs/{key}/body");
3991 assert_eq!(m.params, vec![("key", "abc123")]);
3992
3993 let m = router
3994 .match_path("/docs/abc123/body/sections", Method::Get)
3995 .unwrap();
3996 assert_eq!(m.route.path, "/docs/{key}/body/sections");
3997 assert_eq!(m.params, vec![("key", "abc123")]);
3998
3999 assert!(
4001 router
4002 .match_path("/docs/abc123/other", Method::Get)
4003 .is_none()
4004 );
4005 }
4006
4007 #[test]
4008 fn static_prefix_dead_end_falls_back_to_param_sibling() {
4009 let mut router = Router::new();
4010 router.add(route(Method::Get, "/x/static/only")).unwrap();
4011 router.add(route(Method::Get, "/x/{p}/other")).unwrap();
4012
4013 let m = router.match_path("/x/static/only", Method::Get).unwrap();
4015 assert_eq!(m.route.path, "/x/static/only");
4016 assert!(m.params.is_empty());
4017
4018 let m = router.match_path("/x/static/other", Method::Get).unwrap();
4020 assert_eq!(m.route.path, "/x/{p}/other");
4021 assert_eq!(m.params, vec![("p", "static")]);
4022
4023 let mut router = Router::new();
4026 router.add(route(Method::Get, "/x/static/{a}")).unwrap();
4027 router.add(route(Method::Get, "/x/{p}/other")).unwrap();
4028 let m = router.match_path("/x/static/other", Method::Get).unwrap();
4029 assert_eq!(m.route.path, "/x/static/{a}");
4030 assert_eq!(m.params, vec![("a", "other")]);
4031 }
4032
4033 #[test]
4034 fn intermediate_node_without_routes_is_not_a_match() {
4035 let mut router = Router::new();
4036 router.add(route(Method::Get, "/x/s/list")).unwrap();
4037 router.add(route(Method::Get, "/x/{b}")).unwrap();
4038
4039 let m = router.match_path("/x/s", Method::Get).unwrap();
4042 assert_eq!(m.route.path, "/x/{b}");
4043 assert_eq!(m.params, vec![("b", "s")]);
4044
4045 let m = router.match_path("/x/s/list", Method::Get).unwrap();
4046 assert_eq!(m.route.path, "/x/s/list");
4047 assert!(m.params.is_empty());
4048
4049 let mut router = Router::new();
4051 router.add(route(Method::Post, "/y/{a}")).unwrap();
4052 assert!(matches!(
4053 router.lookup("/y/1", Method::Get),
4054 RouteLookup::MethodNotAllowed { .. }
4055 ));
4056 }
4057
4058 #[test]
4059 fn backtracking_restores_params_of_abandoned_candidates() {
4060 let mut router = Router::new();
4061 router
4062 .add(route(Method::Get, "/r/{first}/{second}/deep"))
4063 .unwrap();
4064 router.add(route(Method::Get, "/r/{only}/flat")).unwrap();
4065
4066 let m = router.match_path("/r/1/flat", Method::Get).unwrap();
4069 assert_eq!(m.route.path, "/r/{only}/flat");
4070 assert_eq!(m.params, vec![("only", "1")]);
4071 }
4072}