Utf8Chunks Repair Invalid Bytes

Split byte input into valid UTF-8 runs and invalid bytes with utf8_chunks, then rebuild the text with U+FFFD replacements like from_utf8_lossy does.

RustData Integrity

Code

snippet
fn main() {
    // 合法 UTF-8 文本与无效字节 0xE9、0xFF 交错出现
    let payload = b"caf\xe9ol\xffxe";

    // utf8_chunks 把字节流切成 valid/invalid 交替的片段
    for chunk in payload.utf8_chunks() {
        println!("valid: {:?} invalid: {:?}", chunk.valid(), chunk.invalid());
    }

    // 修复策略:无效字节替换为 U+FFFD,其余原样保留
    let mut repaired = String::new();
    for chunk in payload.utf8_chunks() {
        repaired.push_str(chunk.valid());
        if !chunk.invalid().is_empty() {
            repaired.push('\u{FFFD}');
        }
    }
    println!("repaired: {repaired}");
    println!(
        "lossy matches repair: {}",
        String::from_utf8_lossy(payload).into_owned() == repaired
    );
}

Watching the values move

Utf8Chunks Repair Invalid Bytes keeps everything in the function main.

Iteration happens inside for chunk in payload.utf8_chunks() — everything outside it runs once.

Points of care

  • Copy, run: the standard library answers every call in the file.

Applying it

The run emits 3 labeled sections — valid:, repaired:, lossy matches repair: — one per step.

Statements that matter

String::from_utf8_lossy(payload).into_owned() == repaired
);
let mut repaired = String::new();
repaired.push_str(chunk.valid());

Interactive Tools for This Topic

FAQ

What does Utf8Chunks Repair Invalid Bytes print when run?
No setup needed: run the file and look for labeled lines like `valid:`, `repaired:`, `lossy matches repair:` in the output.