Zero Copy Chunk Reads With fill_buf
Read a BufReader in zero-copy chunks with fill_buf and consume, bounding each read to the buffer capacity instead of allocating a Vec per segment.
Code
use std::io::{BufRead, BufReader, Cursor};
fn main() {
// 8 字节容量的缓冲:fill_buf 每次最多给 8 字节
let mut reader = BufReader::with_capacity(8, Cursor::new(b"chunk-a|chunk-b|c".to_vec()));
// zero-copy chunk loop:fill_buf 借出内部缓冲,consume 推进读位置
let mut total = 0;
loop {
let chunk = match reader.fill_buf() {
Ok(chunk) if !chunk.is_empty() => chunk,
Ok(_) => break, // 空切片表示 EOF
Err(_) => break,
};
let n = chunk.len();
let text = String::from_utf8_lossy(chunk).into_owned();
println!("read {}: {}", n, text);
reader.consume(n);
total += n;
}
println!("total consumed: {}", total);
}How it works
Zero Copy Chunk Reads With fill_buf reduces to the function main.
A match spells out every case; omit one and the code does not compile.
What to watch for
- Runs with what the toolchain already gives you — nothing extra.
Putting it to use
Entry signature: fn main()
Look for the read, total consumed: prefixes when the file runs; they tie each line to its step.
Core lines
Ok(_) => break, // 空切片表示 EOF
Err(_) => break,
};
Interactive Tools for This Topic
RAG Document Chunk VisualizerSplit long documents into RAG chunks by character or word count with configurable overlap, boundary alignment, token stats, and highlighted overlaps.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 Zero Copy Chunk Reads With fill_buf print when run?
- The script runs standalone; its 2 labeled outputs include `read`, `total consumed:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.