make_ascii_uppercase Rewrites Bytes In Place

Uppercase strings and byte buffers in place with make_ascii_uppercase: no allocation and only a-z are touched, leaving non-ASCII characters untouched.

RustForm Validation

Code

rustsnippet
23 lines
fn normalize_header(raw: &str) -> String {
    // 规范化比较键:ASCII 原地大写,非 ASCII 字符保持原样
    let mut key = raw.to_string();
    key.make_ascii_uppercase();
    key
}

fn main() {
    let inputs = ["content-type", "X-Request-Ïd", "etag"];
    for input in inputs {
        println!("{input} -> {}", normalize_header(input));
    }

    // 字节切片同样有 make_ascii_uppercase:零分配改写缓冲区
    let mut tag = *b"gif89a-mime";
    tag.make_ascii_uppercase();
    println!("bytes: {}", String::from_utf8_lossy(&tag));

    // ASCII 版本只动 a-z:ß 等非 ASCII 字符不会被替换
    let mut mixed = String::from("straße");
    mixed.make_ascii_uppercase();
    println!("ascii only: {mixed}");
}

How it works

make_ascii_uppercase Rewrites Bytes In Place reduces to the functions normalize_header and main.

Iteration happens inside for input in inputs — everything outside it runs once.

Using it

The primary signature is fn normalize_header(raw: &str) -> String

The demo output is labeled (bytes:, ascii only:), so every printed line maps back to its originating operation.

main sequences normalize_header; executing the file runs that flow once.

Key statements

fn normalize_header(raw: &str) -> String {
    // 规范化比较键:ASCII 原地大写,非 ASCII 字符保持原样
    let mut key = raw.to_string();
    key.make_ascii_uppercase();
    key
}

Interactive Tools for This Topic

FAQ

What does make_ascii_uppercase Rewrites Bytes In Place print when run?
Execute the whole file; each printed line is prefixed with a label like `bytes:`, `ascii only:`.