laralang 0.1.0

Localized routes for Laravel Rust: one route per language, translated paths, resources and hreflang alternates.
Documentation
//! URI patterns: filling their placeholders to build a URL, and matching a path against them.

use crate::params::Params;

#[derive(Debug, PartialEq, Eq)]
struct Placeholder<'a> {
    name: &'a str,
    optional: bool,
    wildcard: bool,
}

/// A segment split into its literal text and the placeholder that ends it, if any.
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,
        }),
    )
}

/// The names of a URI's placeholders, in order.
pub fn names(uri: &str) -> Vec<String> {
    uri.split('/')
        .filter_map(|segment| split(segment).1)
        .map(|placeholder| placeholder.name.to_owned())
        .collect()
}

/// Fill a URI's placeholders. The parameters it uses are taken out of `params`.
///
/// # Errors
///
/// Returns why a required placeholder could not be filled.
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("/")))
}

/// Whether a path is one that the URI pattern serves.
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()
}

/// Percent-encode one value so it stays within one segment.
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'~')
    })
}

/// Percent-encode a wildcard's value, keeping its slashes.
fn encode_path(path: &str) -> String {
    path.split('/').map(encode_segment).collect::<Vec<_>>().join("/")
}

/// Percent-encode a URI's literal text as browsers do: reserved characters stay as they are.
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'@'
            )
    })
}

/// Percent-encode a query string component.
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
}

/// Decode a percent-encoded segment. Invalid escapes are kept as they are.
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"));
    }
}