ErrorKind::InvalidData
RustERRORNotableI/O

Invalid data

Quick Answer

Validate data before interpreting; use from_utf8_lossy for lenient UTF-8 decoding.

What this means

Data read from an I/O source is invalid or malformed (e.g. invalid UTF-8, corrupt data).

Why it happens
  1. 1Reading non-UTF-8 bytes with BufReader::lines()
  2. 2Corrupt serialized data
  3. 3TLS certificate parse failure

Fix

Use lossy UTF-8 decoding

Use lossy UTF-8 decoding
let bytes = std::fs::read("file.txt")?;
let text = String::from_utf8_lossy(&bytes);
println!("{}", text); // replaces invalid bytes with �

Why this works

from_utf8_lossy never errors; invalid sequences become the replacement character.

Code examples
Triggerrust
// BufRead::lines() returns InvalidData on non-UTF-8 bytes
Same error in other languages
Sources

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Rust errors