Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

2.1 KB
Raw Blame
/// The parameters of `route` (`/users/{id}`, `/users/id{id}`, `/files/{*rest}`) in `path`, percent-decoded; one
/// whose escapes are not UTF-8 stays as sent.
#[allow(dead_code)]
pub(crate) fn path_params(route: &str, path: &str) -> HashMap<String, String> {
    let mut out = HashMap::new();
    let mut segments = path.trim_start_matches('/').split('/');
    for part in route.trim_start_matches('/').split('/') {
        let segment = segments.next().unwrap_or_default();
        let Some((prefix, name, suffix)) = param(part) else {
            continue;
        };
        if let Some(name) = name.strip_prefix('*') {
            let rest: Vec<&str> = std::iter::once(segment).chain(segments.by_ref()).collect();
            let rest = rest.join("/");
            out.insert(name.to_string(), decode(rest.strip_prefix(&prefix).unwrap_or(&rest)));
            break;
        }
        let value = segment
            .strip_prefix(&prefix)
            .and_then(|v| v.strip_suffix(&suffix))
            .unwrap_or(segment);
        out.insert(name.to_string(), decode(value));
    }
    out
}

#[allow(dead_code)]
fn param(part: &str) -> Option<(String, &str, String)> {
    let unescape = |text: &str| text.replace("{{", "{").replace("}}", "}");
    let mut at = 0;
    while let Some(i) = part[at..].find('{').map(|i| at + i) {
        if part[i..].starts_with("{{") {
            at = i + 2;
            continue;
        }
        let end = i + part[i..].find('}')?;
        return Some((unescape(&part[..i]), &part[i + 1..end], unescape(&part[end + 1..])));
    }
    None
}

#[allow(dead_code)]
fn decode(text: &str) -> String {
    let bytes = text.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        let hex = |at: usize| bytes.get(at).and_then(|b| char::from(*b).to_digit(16));
        if bytes[i] == b'%'
            && let (Some(high), Some(low)) = (hex(i + 1), hex(i + 2))
        {
            out.push((high * 16 + low) as u8);
            i += 3;
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    String::from_utf8(out).unwrap_or_else(|_| text.to_string())
}