Stream Delimited Records With BufRead::split
Iterate NUL-delimited byte records via BufRead::split, skipping empty gaps and turning invalid UTF-8 bytes into io::ErrorKind::InvalidData failures.
Code
use std::io::{self, BufRead, BufReader, Cursor};
fn parse_nul_records<R: BufRead>(reader: R) -> io::Result<Vec<String>> {
let mut records = Vec::new();
for segment in reader.split(b'\0') {
let bytes = segment?;
if bytes.is_empty() {
continue;
}
let text = String::from_utf8(bytes)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
records.push(text);
}
Ok(records)
}
fn main() -> io::Result<()> {
// NUL-delimited stream (such as find -print0 or git diff -z output)
let stream = b"src/main.rs\0\0Cargo.toml\0README.md\0";
let reader = BufReader::new(Cursor::new(stream));
let valid = parse_nul_records(reader)?;
println!("nul records ({}): {valid:?}", valid.len());
let bad_utf8 = b"ok\0\xff\xfe\0";
let err = parse_nul_records(BufReader::new(Cursor::new(bad_utf8))).unwrap_err();
println!("invalid utf8 kind: {:?}", err.kind());
Ok(())
}Execution walkthrough — Stream Delimited Records With BufRead::split
Stream Delimited Records With BufRead::split comes down to the functions parse_nul_records and main.
One loop does the cycling here: for segment in reader.split(b'\0'). Fallible operations return Result, and the ? operator short-circuits errors up to the caller.
What to watch for
- Any import statements resolve solely against stock standard-library modules bundled natively.
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Applying it
The file’s steps show up in the output as nul records (, invalid utf8 kind:.
There are 1 call inside main — parse_nul_records — executed top to bottom.
Statements that matter
let err = parse_nul_records(BufReader::new(Cursor::new(bad_utf8))).unwrap_err();
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let valid = parse_nul_records(reader)?;
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- How do errors reach the caller?
- Each fallible operation returns `Result`; nothing is silently discarded.
- What does Stream Delimited Records With BufRead::split print when run?
- Invoke the file as-is — the `nul records (`, `invalid utf8 kind:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.