实现说明
全部逻辑都在函数 sanitize_header、main中。
for raw in inputs 是唯一的迭代点——其余代码顺序执行一遍。match 逐一列出值的可能形态,漏掉的分支编译器会拒绝。
使用要点
- 依赖清单是空的,语言运行时全覆盖。
main的演示流程是sanitize_header——跑一遍文件,这条流程从头到尾可见。
常见问题
「用 Cow 按需转义避免多余堆分配」这个示例怎么运行?
文件自包含:直接运行,没有需要预先安装的依赖。
主签名形如 fn sanitize_header(value: &str) -> Cow<'_, str>
核心语句
.map(|c| match c {
'\r' | '\n' | '\t' => ' ',
other => other,
})
return Cow::Borrowed(value);
let kind = match &out {
Cow::Borrowed(_) => "borrowed",
Cow::Owned(_) => "owned",
};
代码示例
use std::borrow::Cow;
fn sanitize_header(value: &str) -> Cow<'_, str> {
if !value.bytes().any(|b| b == b'\r' || b == b'\n' || b == b'\t') {
// Zero allocation: return the borrowed input slice directly
return Cow::Borrowed(value);
}
let cleaned: String = value
.chars()
.map(|c| match c {
'\r' | '\n' | '\t' => ' ',
other => other,
})
.collect();
Cow::Owned(cleaned)
}
fn main() {
let inputs = ["Bearer token-abc", "Line1\nLine2\tTail", "x-request-id-42"];
for raw in inputs {
let out = sanitize_header(raw);
let kind = match &out {
Cow::Borrowed(_) => "borrowed",
Cow::Owned(_) => "owned",
};
println!("{raw:?} -> {out:?} ({kind})");
}
}