Avoid Allocations With Cow Conditional Escaping
Return Cow::Borrowed when a header string needs no control-character cleanup, allocating a Cow::Owned String only on inputs that actually change.
Code
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})");
}
}Execution breakdown — Avoid Allocations With Cow Conditional Escaping
Core execution flow is coordinated directly throughs sanitize_header and main.
for raw in inputs is the loop that carries the per-item work. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.
What to watch for
- Completely self-reliant on core stdlib so copy-paste runs immediately.
Using it
Entry signature: fn sanitize_header(value: &str) -> Cow<'_, str>
The demo flow inside main is sanitize_header — run the file to see it end to end.
Key statements
.map(|c| match c {
'\r' | '\n' | '\t' => ' ',
other => other,
})
return Cow::Borrowed(value);
let kind = match &out {
Cow::Borrowed(_) => "borrowed",
Cow::Owned(_) => "owned",
};
Interactive Tools for This Topic
Regex Escape GeneratorEscape plain text so it can be embedded safely in a JavaScript RegExp, covering all metacharacters like dots, brackets, braces, and backslashes.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Avoid Allocations With Cow Conditional Escaping?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.