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.
Code
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
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.JSON Repair & InspectorDeterministically repair malformed JSON with trailing commas, comments, single quotes, unquoted keys, and Python literals alongside a repair log.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
- 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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.