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.
Code
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
Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.