Accept Path And Borrowed Keys With Trait Bounds

Write generic functions over AsRef<Path> to accept any path-like input and Borrow<Q> to query PathBuf HashMap keys using borrowed &Path.

RustSecurity Boundaries

Code

snippet
use std::borrow::Borrow;
use std::collections::HashMap;
use std::hash::Hash;
use std::path::{Component, Path, PathBuf};

fn safe_join<P: AsRef<Path>>(root: &Path, child: P) -> Option<PathBuf> {
    let rel = child.as_ref();
    if rel.is_absolute()
        || rel.has_root()
        || rel.components().any(|c| matches!(c, Component::ParentDir))
    {
        return None;
    }
    Some(root.join(rel))
}

fn lookup<'a, K, Q, V>(index: &'a HashMap<K, V>, key: &Q) -> Option<&'a V>
where
    K: Eq + Hash + Borrow<Q>,
    Q: Eq + Hash + ?Sized,
{
    index.get(key)
}

fn main() {
    let root = Path::new("/srv/uploads");
    let owned = String::from("2026/report.csv");
    println!("from &str:   {:?}", safe_join(root, "avatar.png"));
    println!("from String: {:?}", safe_join(root, &owned));
    println!("traversal:   {:?}", safe_join(root, "../etc/passwd"));

    let routes = HashMap::from([
        (PathBuf::from("avatar.png"), "image/png"),
        (PathBuf::from("2026/report.csv"), "text/csv"),
    ]);
    let target = Path::new("avatar.png");
    // PathBuf implements Borrow<Path>, so &Path looks up without allocating
    println!("mime lookup: {:?}", lookup(&routes, target));
}

Inside the implementation — Accept Path And Borrowed Keys With Trait Bounds

The snippet is organized around the functions safe_join, lookup and main.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

Output lines are prefixed (from &str:, from String:, traversal:), exposing individual computation results clearly across printed rows.

The sequence safe_join and lookup lives in main; running the file triggers it.

Key statements

fn safe_join<P: AsRef<Path>>(root: &Path, child: P) -> Option<PathBuf> {
    let rel = child.as_ref();
    if rel.is_absolute()
        || rel.has_root()
        || rel.components().any(|c| matches!(c, Component::ParentDir))
    {
        return None;
    }
    Some(root.join(rel))
}
fn lookup<'a, K, Q, V>(index: &'a HashMap<K, V>, key: &Q) -> Option<&'a V>
where
    K: Eq + Hash + Borrow<Q>,
    Q: Eq + Hash + ?Sized,
{
    index.get(key)
}

Interactive Tools for This Topic

FAQ

What does Accept Path And Borrowed Keys With Trait Bounds print when run?
Invoke the file as-is — the `from &str:`, `from String:`, `traversal:` prefixes identify which step printed each line.