1use core::fmt;
4
5use percent_encoding::{AsciiSet, CONTROLS, utf8_percent_encode};
6use serde::Serialize;
7
8use crate::router::Pattern;
9
10const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
12
13pub fn href(pattern: &str) -> Href {
40 Href {
41 pattern: Pattern::parse(pattern),
42 params: Vec::new(),
43 query: None,
44 fragment: None,
45 }
46}
47
48#[derive(Debug, Clone)]
51#[must_use]
52pub struct Href {
53 pattern: Pattern,
54 params: Vec<(String, String)>,
55 query: Option<String>,
56 fragment: Option<String>,
57}
58
59impl Href {
60 pub fn param(mut self, name: &str, value: impl fmt::Display) -> Self {
65 assert!(
66 self.pattern.has_param(name),
67 "`{}` has no parameter `{name}`",
68 self.pattern.as_str()
69 );
70 let value = value.to_string();
71 match self.params.iter_mut().find(|(param, _)| param == name) {
72 Some((_, old)) => *old = value,
73 None => self.params.push((name.to_owned(), value)),
74 }
75 self
76 }
77
78 pub fn query(mut self, query: &impl Serialize) -> Self {
84 let query = serde_urlencoded::to_string(query)
85 .unwrap_or_else(|error| panic!("href: can't serialize the query: {error}"));
86 self.query = Some(query).filter(|query| !query.is_empty());
87 self
88 }
89
90 pub fn fragment(mut self, fragment: &str) -> Self {
93 self.fragment = Some(utf8_percent_encode(fragment, FRAGMENT).to_string());
94 self
95 }
96}
97
98impl fmt::Display for Href {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 f.write_str(&self.pattern.fill(&self.params))?;
101 if let Some(query) = &self.query {
102 write!(f, "?{query}")?;
103 }
104 if let Some(fragment) = &self.fragment {
105 write!(f, "#{fragment}")?;
106 }
107 Ok(())
108 }
109}
110
111impl From<Href> for String {
112 fn from(href: Href) -> Self {
113 href.to_string()
114 }
115}
116
117#[cfg(test)]
118mod tests {
119 use serde::Serialize;
120
121 use super::href;
122
123 #[derive(Serialize)]
124 struct Filter {
125 tag: Option<&'static str>,
126 q: &'static str,
127 }
128
129 #[test]
130 fn params() {
131 let url = href("/users/{id=int}/{?tab}").param("id", 7);
132 assert_eq!(url.to_string(), "/users/7");
133 let url = url.param("tab", "posts").param("id", 8);
134 assert_eq!(String::from(url), "/users/8/posts");
135 let url = href("/files/{*path}").param("path", "a b/c?");
136 assert_eq!(url.to_string(), "/files/a%20b/c%3F");
137 }
138
139 #[test]
140 fn query_and_fragment() {
141 let filter = Filter {
142 tag: None,
143 q: "a&b c",
144 };
145 let url = href("/blog").query(&filter).fragment("top");
146 assert_eq!(url.to_string(), "/blog?q=a%26b+c#top");
147 let url = href("/blog").query(&[("tag", "x")]).query(&());
148 assert_eq!(url.to_string(), "/blog");
149 assert_eq!(href("/").fragment("a b").to_string(), "/#a%20b");
150 }
151
152 #[test]
153 #[should_panic(expected = "`/blog/{slug}` is missing the parameter `slug`")]
154 fn missing_param() {
155 let _ = href("/blog/{slug}").to_string();
156 }
157
158 #[test]
159 #[should_panic(expected = "`/blog/{slug}` has no parameter `id`")]
160 fn unknown_param() {
161 let _ = href("/blog/{slug}").param("id", 1);
162 }
163
164 #[test]
165 #[should_panic(expected = "href: can't serialize the query")]
166 fn nested_query() {
167 #[derive(Serialize)]
168 struct Outer {
169 inner: Filter,
170 }
171 let outer = Outer {
172 inner: Filter { tag: None, q: "" },
173 };
174 let _ = href("/").query(&outer);
175 }
176
177 #[test]
178 #[should_panic(expected = "invalid route")]
179 fn invalid_pattern() {
180 let _ = href("/{*rest}/x");
181 }
182}