use super::ctx::RouteParams;
use super::route::AccessPolicy;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Method {
Get,
Post,
Patch,
Delete,
}
impl Method {
pub fn parse(raw: &str) -> Option<Self> {
match raw {
"GET" => Some(Self::Get),
"POST" => Some(Self::Post),
"PATCH" => Some(Self::Patch),
"DELETE" => Some(Self::Delete),
_ => None,
}
}
pub const fn as_str(self) -> &'static str {
match self {
Self::Get => "GET",
Self::Post => "POST",
Self::Patch => "PATCH",
Self::Delete => "DELETE",
}
}
}
#[derive(Debug, Clone)]
pub struct RouteDef<H> {
pub method: Method,
pub pattern: &'static str,
pub policy: AccessPolicy,
pub handler: H,
}
#[derive(Debug, Clone)]
enum Segment {
Static(&'static str),
Param(&'static str),
Wildcard(&'static str),
}
struct CompiledRoute<H> {
def: RouteDef<H>,
segments: Vec<Segment>,
}
#[derive(Debug)]
pub enum RouteMatch<'a, H> {
Matched {
route: &'a RouteDef<H>,
params: RouteParams,
},
MethodNotAllowed {
allow: Vec<Method>,
},
NotFound,
}
pub struct Router<H> {
routes: Vec<CompiledRoute<H>>,
}
impl<H> Default for Router<H> {
fn default() -> Self {
Self::new()
}
}
impl<H> Router<H> {
pub fn new() -> Self {
Self { routes: Vec::new() }
}
pub fn add(
&mut self,
method: Method,
pattern: &'static str,
policy: AccessPolicy,
handler: H,
) -> &mut Self {
let segments = compile_pattern(pattern);
self.routes.push(CompiledRoute {
def: RouteDef {
method,
pattern,
policy,
handler,
},
segments,
});
self
}
pub fn get(&mut self, pattern: &'static str, policy: AccessPolicy, handler: H) -> &mut Self {
self.add(Method::Get, pattern, policy, handler)
}
pub fn post(&mut self, pattern: &'static str, policy: AccessPolicy, handler: H) -> &mut Self {
self.add(Method::Post, pattern, policy, handler)
}
pub fn match_request(&self, method_str: &str, path: &str) -> RouteMatch<'_, H> {
let req_method = if method_str == "HEAD" {
Some(Method::Get)
} else {
Method::parse(method_str)
};
let path_segs: Vec<&str> = split_segments(path);
let mut allowed: Vec<Method> = Vec::new();
for compiled in &self.routes {
if let Some(params) = match_segments(&compiled.segments, &path_segs) {
if req_method == Some(compiled.def.method) {
return RouteMatch::Matched {
route: &compiled.def,
params,
};
}
if !allowed.contains(&compiled.def.method) {
allowed.push(compiled.def.method);
}
}
}
if !allowed.is_empty() {
RouteMatch::MethodNotAllowed { allow: allowed }
} else {
RouteMatch::NotFound
}
}
pub fn allowed_methods(&self, path: &str) -> Vec<Method> {
let path_segs: Vec<&str> = split_segments(path);
let mut allowed: Vec<Method> = Vec::new();
for compiled in &self.routes {
if match_segments(&compiled.segments, &path_segs).is_some()
&& !allowed.contains(&compiled.def.method)
{
allowed.push(compiled.def.method);
}
}
allowed
}
}
pub fn format_allow_header(methods: &[Method]) -> String {
let mut parts: Vec<&'static str> = Vec::with_capacity(methods.len() + 2);
for &m in methods {
parts.push(m.as_str());
if m == Method::Get && !parts.contains(&"HEAD") {
parts.push("HEAD");
}
}
if !parts.is_empty() && !parts.contains(&"OPTIONS") {
parts.push("OPTIONS");
}
parts.join(", ")
}
fn split_segments(path: &str) -> Vec<&str> {
let trimmed = path.trim_matches('/');
if trimmed.is_empty() {
Vec::new()
} else {
trimmed.split('/').collect()
}
}
fn compile_pattern(pattern: &'static str) -> Vec<Segment> {
split_segments(pattern)
.into_iter()
.map(|seg| {
if let Some(name) = seg.strip_prefix(':') {
Segment::Param(name)
} else if let Some(name) = seg.strip_prefix('*') {
Segment::Wildcard(name)
} else {
Segment::Static(seg)
}
})
.collect()
}
fn match_segments(pattern: &[Segment], input: &[&str]) -> Option<RouteParams> {
let mut params = RouteParams::new();
let mut pi = 0usize;
let mut ii = 0usize;
while pi < pattern.len() {
match pattern[pi] {
Segment::Static(lit) => {
if input.get(ii).copied() != Some(lit) {
return None;
}
pi += 1;
ii += 1;
}
Segment::Param(name) => {
let val = *input.get(ii)?;
if val.is_empty() {
return None;
}
params.insert(name, val);
pi += 1;
ii += 1;
}
Segment::Wildcard(name) => {
let tail = if ii < input.len() {
input[ii..].join("/")
} else {
String::new()
};
params.insert(name, tail);
return Some(params);
}
}
}
if ii == input.len() {
Some(params)
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn router_matches_static_param_wildcard_and_405() {
let mut r: Router<&'static str> = Router::new();
r.get("/", AccessPolicy::ReadRepo, "home")
.get("/pulls/new", AccessPolicy::ReadRepo, "pr_new")
.get("/pulls/:branch", AccessPolicy::ReadRepo, "pr_detail")
.post(
"/issues/:id/comment",
AccessPolicy::WriteRepo,
"issue_comment",
)
.get("/blob/:rev/*path", AccessPolicy::ReadRepo, "blob");
match r.match_request("GET", "/pulls/new") {
RouteMatch::Matched { route, .. } => assert_eq!(route.handler, "pr_new"),
other => panic!("expected pr_new, got {other:?}"),
}
match r.match_request("GET", "/pulls/feature-1") {
RouteMatch::Matched { route, params } => {
assert_eq!(route.handler, "pr_detail");
assert_eq!(params.get("branch"), Some("feature-1"));
}
other => panic!("expected pr_detail, got {other:?}"),
}
match r.match_request("GET", "/blob/main/crates/arks/src/main.rs") {
RouteMatch::Matched { route, params } => {
assert_eq!(route.handler, "blob");
assert_eq!(params.get("rev"), Some("main"));
assert_eq!(params.get("path"), Some("crates/arks/src/main.rs"));
}
other => panic!("expected blob, got {other:?}"),
}
match r.match_request("GET", "/issues/7/comment") {
RouteMatch::MethodNotAllowed { allow } => assert_eq!(allow, vec![Method::Post]),
other => panic!("expected 405, got {other:?}"),
}
assert!(matches!(
r.match_request("GET", "/unknown"),
RouteMatch::NotFound
));
}
}