Skip to main content

next_rust_router/
params.rs

1use serde::{Deserialize, Serialize};
2
3/// Value of a route parameter.
4#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
5#[serde(untagged)]
6pub enum ParamValue {
7    /// `[id]`
8    One(String),
9    /// `[...slug]` and `[[...slug]]`
10    Many(Vec<String>),
11}
12
13/// Route parameters captured while matching, in pattern order.
14#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
15#[serde(
16    from = "std::collections::BTreeMap<String, ParamValue>",
17    into = "std::collections::BTreeMap<String, ParamValue>"
18)]
19pub struct Params(Vec<(String, ParamValue)>);
20
21impl Params {
22    pub fn new() -> Self {
23        Self(Vec::new())
24    }
25
26    /// Builder helper: `Params::new().with("slug", "hello")`.
27    pub fn with(mut self, name: impl Into<String>, value: impl Into<ParamValue>) -> Self {
28        self.insert(name, value);
29        self
30    }
31
32    pub fn insert(&mut self, name: impl Into<String>, value: impl Into<ParamValue>) {
33        let name = name.into();
34        let value = value.into();
35        if let Some(slot) = self.0.iter_mut().find(|(n, _)| *n == name) {
36            slot.1 = value;
37        } else {
38            self.0.push((name, value));
39        }
40    }
41
42    pub(crate) fn pop(&mut self) {
43        self.0.pop();
44    }
45
46    /// Single-segment value. For catch-all params this returns the segments
47    /// joined by `/`… use [`Params::get_all`] to obtain them individually.
48    pub fn get(&self, name: &str) -> Option<&str> {
49        self.0.iter().find(|(n, _)| n == name).and_then(|(_, v)| match v {
50            ParamValue::One(s) => Some(s.as_str()),
51            ParamValue::Many(_) => None,
52        })
53    }
54
55    /// Catch-all segments (`[...slug]`). A single `[id]` value is returned as
56    /// a one element slice.
57    pub fn get_all(&self, name: &str) -> Option<&[String]> {
58        self.0.iter().find(|(n, _)| n == name).map(|(_, v)| match v {
59            ParamValue::One(s) => std::slice::from_ref(s),
60            ParamValue::Many(v) => v.as_slice(),
61        })
62    }
63
64    pub fn value(&self, name: &str) -> Option<&ParamValue> {
65        self.0.iter().find(|(n, _)| n == name).map(|(_, v)| v)
66    }
67
68    pub fn iter(&self) -> impl Iterator<Item = (&str, &ParamValue)> {
69        self.0.iter().map(|(n, v)| (n.as_str(), v))
70    }
71
72    pub fn len(&self) -> usize {
73        self.0.len()
74    }
75
76    pub fn is_empty(&self) -> bool {
77        self.0.is_empty()
78    }
79}
80
81impl From<&str> for ParamValue {
82    fn from(s: &str) -> Self {
83        ParamValue::One(s.to_owned())
84    }
85}
86
87impl From<&String> for ParamValue {
88    fn from(s: &String) -> Self {
89        ParamValue::One(s.clone())
90    }
91}
92
93impl From<String> for ParamValue {
94    fn from(s: String) -> Self {
95        ParamValue::One(s)
96    }
97}
98
99impl From<Vec<String>> for ParamValue {
100    fn from(v: Vec<String>) -> Self {
101        ParamValue::Many(v)
102    }
103}
104
105impl From<Vec<&str>> for ParamValue {
106    fn from(v: Vec<&str>) -> Self {
107        ParamValue::Many(v.into_iter().map(str::to_owned).collect())
108    }
109}
110
111impl<const N: usize> From<[&str; N]> for ParamValue {
112    fn from(v: [&str; N]) -> Self {
113        ParamValue::Many(v.iter().map(|s| (*s).to_owned()).collect())
114    }
115}
116
117impl From<std::collections::BTreeMap<String, ParamValue>> for Params {
118    fn from(map: std::collections::BTreeMap<String, ParamValue>) -> Self {
119        Params(map.into_iter().collect())
120    }
121}
122
123impl From<Params> for std::collections::BTreeMap<String, ParamValue> {
124    fn from(p: Params) -> Self {
125        p.0.into_iter().collect()
126    }
127}
128
129impl<K: Into<String>, V: Into<ParamValue>> FromIterator<(K, V)> for Params {
130    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
131        let mut p = Params::new();
132        for (k, v) in iter {
133            p.insert(k, v);
134        }
135        p
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    #[test]
144    fn values_come_from_every_string_shape() {
145        let owned = String::from("hello");
146        let params =
147            Params::new().with("a", "hello").with("b", owned.clone()).with("c", &owned).with("d", vec!["x", "y"]);
148        assert_eq!(params.get("a"), Some("hello"));
149        assert_eq!(params.get("b"), Some("hello"));
150        assert_eq!(params.get("c"), Some("hello"));
151        assert_eq!(params.get_all("d"), Some(&["x".to_owned(), "y".to_owned()][..]));
152    }
153}