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.

RustData Integrity

Code

snippet
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

FAQ

How do you run Avoid Allocations With Cow Conditional Escaping?
The file is self-contained: run it directly, no dependencies to install beforehand.