Skip to main content

serenade_http/
route.rs

1//! Named route definition and collection.
2
3use std::collections::HashMap;
4
5use crate::Method;
6
7/// A single route: name, path pattern, and allowed methods.
8///
9/// Path segments wrapped in `{…}` are parameters (for example `/items/{id}`).
10#[derive(Clone, Debug, Eq, PartialEq)]
11pub struct Route {
12    name: String,
13    path: String,
14    methods: Vec<Method>,
15}
16
17impl Route {
18    /// Creates a route. Empty `methods` means any method matches.
19    #[must_use]
20    pub fn new(
21        name: impl Into<String>,
22        path: impl Into<String>,
23        methods: impl IntoIterator<Item = Method>,
24    ) -> Self {
25        Self {
26            name: name.into(),
27            path: path.into(),
28            methods: methods.into_iter().collect(),
29        }
30    }
31
32    /// Convenience for a single-method route.
33    #[must_use]
34    pub fn with_method(name: impl Into<String>, path: impl Into<String>, method: Method) -> Self {
35        Self::new(name, path, [method])
36    }
37
38    /// Route name (unique within a collection).
39    #[must_use]
40    pub fn name(&self) -> &str {
41        &self.name
42    }
43
44    /// Path pattern.
45    #[must_use]
46    pub fn path(&self) -> &str {
47        &self.path
48    }
49
50    /// Allowed methods. Empty means any method.
51    #[must_use]
52    pub fn methods(&self) -> &[Method] {
53        &self.methods
54    }
55
56    /// Whether `method` is allowed.
57    #[must_use]
58    pub fn allows(&self, method: Method) -> bool {
59        self.methods.is_empty() || self.methods.contains(&method)
60    }
61}
62
63/// Ordered list of routes. First match wins.
64#[derive(Clone, Debug, Default)]
65pub struct RouteCollection {
66    routes: Vec<Route>,
67}
68
69impl RouteCollection {
70    /// Empty collection.
71    #[must_use]
72    pub fn new() -> Self {
73        Self::default()
74    }
75
76    /// Appends a route.
77    ///
78    /// # Errors
79    ///
80    /// Returns [`crate::HttpError`] when another route already uses the same name.
81    pub fn add(&mut self, route: Route) -> Result<(), crate::HttpError> {
82        if self
83            .routes
84            .iter()
85            .any(|existing| existing.name() == route.name())
86        {
87            return Err(crate::HttpError::failed(format!(
88                "route `{}` is already registered",
89                route.name()
90            )));
91        }
92        self.routes.push(route);
93        Ok(())
94    }
95
96    /// Looks up a route by name.
97    #[must_use]
98    pub fn get(&self, name: &str) -> Option<&Route> {
99        self.routes.iter().find(|route| route.name() == name)
100    }
101
102    /// Builds a path for the named route by substituting `{param}` segments.
103    ///
104    /// Values are percent-encoded as path segments. Every pattern parameter must
105    /// be provided; unused keys are rejected.
106    ///
107    /// # Errors
108    ///
109    /// - Status **404** when `name` is not registered.
110    /// - Status **400** when a required parameter is missing or an unused key remains.
111    pub fn generate(
112        &self,
113        name: &str,
114        params: &[(&str, &str)],
115    ) -> Result<String, crate::HttpError> {
116        let route = self
117            .get(name)
118            .ok_or_else(|| crate::HttpError::status(404, format!("no route named `{name}`")))?;
119        let mut unused: HashMap<&str, &str> = HashMap::with_capacity(params.len());
120        for &(key, value) in params {
121            if unused.insert(key, value).is_some() {
122                return Err(crate::HttpError::status(
123                    400,
124                    format!("duplicate parameter `{key}` for route `{name}`"),
125                ));
126            }
127        }
128        let segments = split_segments(route.path());
129        let mut out = Vec::with_capacity(segments.len());
130        for segment in segments {
131            if let Some(param) = parameter_name(segment) {
132                let Some(value) = unused.remove(param) else {
133                    return Err(crate::HttpError::status(
134                        400,
135                        format!("missing parameter `{param}` for route `{name}`"),
136                    ));
137                };
138                out.push(encode_path_segment(value));
139            } else {
140                out.push(segment.to_owned());
141            }
142        }
143        if let Some((extra, _)) = unused.iter().next() {
144            return Err(crate::HttpError::status(
145                400,
146                format!("unused parameter `{extra}` for route `{name}`"),
147            ));
148        }
149        if out.is_empty() {
150            return Ok("/".to_owned());
151        }
152        Ok(format!("/{}", out.join("/")))
153    }
154
155    /// Registered routes in order.
156    #[must_use]
157    pub fn routes(&self) -> &[Route] {
158        &self.routes
159    }
160
161    /// Number of routes.
162    #[must_use]
163    pub const fn len(&self) -> usize {
164        self.routes.len()
165    }
166
167    /// Whether the collection is empty.
168    #[must_use]
169    pub const fn is_empty(&self) -> bool {
170        self.routes.is_empty()
171    }
172}
173
174pub fn split_segments(path: &str) -> Vec<&str> {
175    path.trim_matches('/')
176        .split('/')
177        .filter(|s| !s.is_empty())
178        .collect()
179}
180
181pub fn parameter_name(segment: &str) -> Option<&str> {
182    segment
183        .strip_prefix('{')
184        .and_then(|rest| rest.strip_suffix('}'))
185        .filter(|name| !name.is_empty())
186}
187
188fn encode_path_segment(value: &str) -> String {
189    let mut out = String::with_capacity(value.len());
190    for byte in value.bytes() {
191        match byte {
192            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
193                out.push(char::from(byte));
194            }
195            _ => {
196                let _ = std::fmt::Write::write_fmt(&mut out, format_args!("%{byte:02X}"));
197            }
198        }
199    }
200    out
201}