实现说明
用 AsRefsafe_join、lookup、main。
使用要点
- 不依赖任何第三方包,全部使用语言内建 API。
- 跑完文件,输出里会留下标记——
from &str:、from String:、traversal:。 main按顺序串起safe_join、lookup;运行文件就会把这个流程跑一遍。
常见问题
运行「用 AsRef
运行文件本身,from &str:、from String:、traversal: 这些前缀各对应一段演示逻辑。
核心语句
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)
}
代码示例
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));
}