use crate::params::Params;
#[derive(Debug, PartialEq, Eq)]
struct Placeholder<'a> {
name: &'a str,
optional: bool,
wildcard: bool,
}
fn split(segment: &str) -> (&str, Option<Placeholder<'_>>) {
let Some(start) = segment.find('{') else {
return (segment, None);
};
let inner = segment[start + 1..].trim_end_matches('}');
let wildcard = inner.starts_with('*');
let inner = inner.trim_start_matches('*');
let optional = inner.ends_with('?');
let inner = inner.trim_end_matches('?');
let name = inner.split(':').next().unwrap_or(inner);
(
&segment[..start],
Some(Placeholder {
name,
optional,
wildcard,
}),
)
}
pub fn names(uri: &str) -> Vec<String> {
uri.split('/')
.filter_map(|segment| split(segment).1)
.map(|placeholder| placeholder.name.to_owned())
.collect()
}
pub fn fill(uri: &str, params: &mut Params) -> Result<String, String> {
let mut segments: Vec<String> = Vec::new();
for segment in uri.trim_start_matches('/').split('/') {
let (text, placeholder) = split(segment);
let Some(placeholder) = placeholder else {
segments.push(encode_static(segment));
continue;
};
let value = params.take(placeholder.name).filter(|value| !value.is_empty());
match value {
Some(value) if placeholder.wildcard => {
segments.push(format!("{}{}", encode_static(text), encode_path(&value)));
}
Some(value) => segments.push(format!("{}{}", encode_static(text), encode_segment(&value))),
None if placeholder.optional && text.is_empty() => {}
None if placeholder.optional => segments.push(encode_static(text)),
None => {
return Err(format!(
"missing the required parameter `{}` of the route `{uri}`",
placeholder.name
));
}
}
}
Ok(format!("/{}", segments.join("/")))
}
pub fn matches(uri: &str, path: &str) -> bool {
let wanted: Vec<&str> = uri
.trim_matches('/')
.split('/')
.filter(|part| !part.is_empty())
.collect();
let given: Vec<String> = path
.trim_matches('/')
.split('/')
.filter(|part| !part.is_empty())
.map(decode)
.collect();
let mut index = 0;
for (position, segment) in wanted.iter().enumerate() {
let (text, placeholder) = split(segment);
let Some(placeholder) = placeholder else {
if given.get(index).is_some_and(|part| *part == decode(segment)) {
index += 1;
continue;
}
return false;
};
if placeholder.wildcard {
return position == wanted.len() - 1 && given.len() > index;
}
match given.get(index) {
Some(part) if part.len() > text.len() && part.starts_with(&decode(text)) => index += 1,
Some(_) => return false,
None if placeholder.optional && text.is_empty() => {}
None => return false,
}
}
index == given.len()
}
pub fn encode_segment(segment: &str) -> String {
match segment {
"." => return "%2E".to_owned(),
".." => return "%2E%2E".to_owned(),
_ => {}
}
encode(segment, |byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~')
})
}
fn encode_path(path: &str) -> String {
path.split('/').map(encode_segment).collect::<Vec<_>>().join("/")
}
fn encode_static(text: &str) -> String {
encode(text, |byte| {
byte.is_ascii_alphanumeric()
|| matches!(
byte,
b'-' | b'.'
| b'_'
| b'~'
| b'!'
| b'$'
| b'&'
| b'\''
| b'('
| b')'
| b'*'
| b'+'
| b','
| b';'
| b'='
| b':'
| b'@'
)
})
}
pub fn encode_query(value: &str) -> String {
encode(value, |byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~')
})
}
fn encode(text: &str, keep: impl Fn(u8) -> bool) -> String {
let mut encoded = String::with_capacity(text.len());
for byte in text.bytes() {
if keep(byte) {
encoded.push(byte as char);
} else {
encoded.push_str(&format!("%{byte:02X}"));
}
}
encoded
}
pub fn decode(segment: &str) -> String {
let bytes = segment.as_bytes();
let mut decoded = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
if bytes[index] == b'%'
&& let Some(hex) = segment.get(index + 1..index + 3)
&& let Ok(byte) = u8::from_str_radix(hex, 16)
{
decoded.push(byte);
index += 3;
continue;
}
decoded.push(bytes[index]);
index += 1;
}
String::from_utf8_lossy(&decoded).into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fills_placeholders_and_encodes_values() {
let mut params = Params::new().with("slug", "hola mundo/ñ");
assert_eq!(
fill("/es/articulos/{slug}", &mut params).unwrap(),
"/es/articulos/hola%20mundo%2F%C3%B1"
);
}
#[test]
fn leaves_out_trailing_optional_parameters() {
assert_eq!(fill("/blog/{page?}", &mut Params::new()).unwrap(), "/blog");
assert_eq!(
fill("/blog/{page?}", &mut Params::new().with("page", 2)).unwrap(),
"/blog/2"
);
}
#[test]
fn a_missing_required_parameter_is_an_error() {
assert!(fill("/blog/{slug}", &mut Params::new()).is_err());
}
#[test]
fn matches_static_parameterized_and_wildcard_patterns() {
assert!(matches("/es/servicios", "/es/servicios"));
assert!(matches("/propiedad/{slug}", "/propiedad/piso-centro"));
assert!(!matches("/propiedad/{slug}", "/propiedad"));
assert!(!matches("/propiedad/{slug}", "/propiedad/a/b"));
assert!(matches("/blog/{page?}", "/blog"));
assert!(matches("/files/{*path}", "/files/a/b/c"));
assert!(matches("/users/user-{id}", "/users/user-7"));
assert!(!matches("/users/user-{id}", "/users/user-"));
assert!(matches("/café", "/caf%C3%A9"));
}
}